Prashanth Chandra Prashanth Chandra - 2 months ago 78
TypeScript Question

How to automatically add types declaration for a library to tsconfig.json in TypeScript 2.0?

TypeScript 2.0 comes with a new way of fetching type declarations using npm packages under the @types scope.

npm i --save-dev @types/lodash


According to this answer, one can tell TypeScript where to look for TypeScript type declaration files by adding a string to the
typings
property of
tsconfig.json
, which is also documented here.

{
"compilerOptions": {
...
"types": ["lodash"]
}
}


It seems tedious to have to manually edit
tsconfig.json
every time I install a new type declaration. Is there a way to do this automatically?

I was thinking of writing an npm script for it but I was hoping I wouldn't have to resort to using bash to edit a JSON file.

Answer

If you are using the new @Types definitions, you can simply add the typeRoots option and specify the folder. i.e. "typeRoots": [ "node_modules/@types" ]. It will parse through that folder and pick up all the types you have installed, and you don't have to add the /// reference

Comments