Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does /// <reference types="node" /> mean?

Tags:

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?

like image 712
cham Avatar asked Jan 11 '18 21:01

cham


People also ask

What is types node used for?

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.

What does @types mean NPM?

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.

What is reference in TypeScript?

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.

Do we need types node?

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.


1 Answers

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.

like image 85
casieber Avatar answered Oct 07 '22 08:10

casieber