I am trying to get my first TypeScript and DefinitelyTyped Node.js application up and running, and running into some errors.
I am getting the error \"TS2304: Cannot
This answer relates to modern setups (TypeScript 2.x, Webpack > 2.x)
You don't need to install @types/node (which is all of Node.js types and is irrelevant for front-end code, actually complicating things such as setTimout different return values, etc..
You do need to install @types/webpack-env
npm i -D @types/webpack-env
which gives the runtime signatures that Webpack has (including require
, require.ensure
, etc.)
Also make sure that your tsconfig.json file has no set 'types' array -> which will make it pickup all type definitions in your node_modules/@types folder.
If you want to restrict search of types you can set the typeRoot property to node_modules/@types.
Instead of:
'use strict';
/// <reference path="typings/tsd.d.ts" />
Try:
/// <reference path="typings/tsd.d.ts" />
'use strict';
i.e. reference path first.
I found the solution was to use the TSD command:
tsd install node --save
Which adds/updates the typings/tsd.d.ts
file and that file contains all the type definitions that are required for a node application.
At the top of my file, I put a reference to the tsd.d.ts
like this:
/// <reference path="../typings/tsd.d.ts" />
The require is defined like this as of January 2016:
declare var require: NodeRequire;
interface NodeModule {
exports: any;
require: NodeRequireFunction;
id: string;
filename: string;
loaded: boolean;
parent: any;
children: any[];
}
Add the following in tsconfig.json
:
"typeRoots": [ "../node_modules/@types" ]
I've yet another answer that builds upon all previous ones that describe npm install @types/node
and including node
in tsconfig.json / compilerOptions / types
.
In my case, I have a base tsConfig.json
and a separate one in the Angular application that extends this one:
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"types": []
},
My problem was the empty types
in this tsconfi.app.json
- it clobbers the one in the base configuration.
As approved answer didn't mention possibility to actually create your own typings file, and import it there, let me add it below.
Assuming you use npm as your package manager, you can:
npm i @types/node --save-dev
Then in your tsconfig file:
"include": ["typings.d.ts"],
Then create your typings file:
import 'node/globals'
Done, errors are gone, enjoy TypeScript :)