I was having a problem with typescript and node and stumbled on a fix (I was getting a TS complaint that 'process' was not defined, as in process.env in Node). All I had to do was paste one line at the top of my file:
/// <reference types="node" />
I don't understand the syntax. Is the typescript compiler somehow reading a comment? How does this work?
This package contains type definitions for Node. js (http://nodejs.org/). This package is used to load in all type definitions when using typescript in node. When you add other packages, you also have to add their typings if they do not include them by default.
The @types npm organization is for obtaining type definitions with npm . Using these type definitions is a feature is coming in TypeScript 2.0. This will replace the current projects/tools such as typings and tsd, though these will continue to be supported for some time. Follow this answer to receive notifications.
Project references are a new feature in TypeScript 3.0 that allow you to structure your TypeScript programs into smaller pieces. By doing this, you can greatly improve build times, enforce logical separation between components, and organize your code in new and better ways.
Using Node require in Typescript programs What is happening here is that we have no type definition for this global function named require . The Node runtime does not ship with its own type definitions, so we need to import those types separately.
These are referred to as "Triple Slash Directives" (Typescript docs)
As stated on the first line of that link:
Triple-slash directives are single-line comments containing a single XML tag. The contents of the comment are used as compiler directives.
So yes, the typescript compiler is picking this up during compilation and taking the appropriate action.
In this case, since you are using a types
directive, you are telling the compiler that this file has a dependency on the node
typings.
That said, the docs also state that for types
directives:
Use these directives only when you're authoring a
d.ts
file by hand
So if you have added this do a .ts
file rather than a .d.ts
file, you may be setting yourself up for further problems.
For declaring a dependency on an @types package in a .ts file, use --types on the command line or in your tsconfig.json instead. See using @types, typeRoots and types in tsconfig.json files for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With