Prologue
Buffer is part of the Node.js API. Because TypeScript doesn't know classes from Node.js by default, you will need to install declaration files (type definitions) for Node.js.
If you see the following error, you will have to install type definitions manually:
error TS2304: Cannot find name 'Buffer'.
Installing Type Definitions
You can install type definitions using the typings tool. I will show you how to do this:
Install the typings
tool with npm:
npm install -g typings
Install type definitions for Node.js from the DefinitelyTyped (~dt
) repository:
typings install dt~node --global --save
The typings tool will create the following directory "typings/globals/node
" and link it in "typings/index.d.ts
". There will be also a file called typings.json
(because of the --save
option), which references the resolved type definitions:
{
"globalDependencies": {
"node": "registry:dt/node#6.0.0+20160621231320"
}
}
Note: If you see the error "typings\globals\node\index.d.ts(71,26): error TS1110: Type expected", then your Node.js definition is too recent. The typings tool has issues with latest type declarations. In such a case, just check the version in your typings.json
file. For me node#6.0.0+20160621231320
was working but node#6.0.0+20161212163245
was not.
- Now all you have to do is adding
index.d.ts
as a triple-slash directive within your code (which uses the Buffer
class):
YourClass.ts
/// <reference path="../../typings/index.d.ts" />
export class YourClass {
private static toString(encoded: string): string {
return new Buffer(encoded, "base64").toString();
}
}
UPDATE:
With the release of TypeScript 2.0 a new type definitions system has been announced.
You can now forget about the typings
tool. All you need to do is running this command to install TypeScript definitions for Node.js:
npm install --save @types/node
Please also make sure that you have the following entries in your tsconfig.json
:
{
"compilerOptions": {
"moduleResolution": "node",
...
},
"exclude": [
"node_modules",
...
]
}
P.S. If you need type definitions for other classes (than included in Node.js), you can search for them here: http://microsoft.github.io/TypeSearch/
npm i --save-dev @types/node
. Dev dependencies! – Lula