Typescript 2.0. "types" field in tsconfig.json

As of TypeScript 2.* the 'tsconfig.json' has the following two properties available:

{
    'typeRoots': [],
    'types': [] 
}

I'll detail both in order.


  1. 'typeRoots' specifies root folders in which the transpiler should look for type definitions (eg: 'node_modules').

    • If you've been using typescript, you know that for different libraries that have not been written using typescript, you need definitions in order for the compiler to recognize global variables and to have IntelliSense support.

    • This issue has been tackled by projects (repos) such as 'DefinatelyTyped' that use tools such as tsd or typings module to download typings required for your project, but they also come with their own 'json' file that needs to be maintained separately.

    • With TS2.* you can now fetch definition dependencies using 'npm'. So instead of using a seperate cli library like tsd or typings, you can now just use: npm i @types/{LIB} this way, all dependencies are managed using package.json and you can easily eliminate the necessity of another 'json' file to maintain in your project.


  1. 'types' are the actual library names that will be found in the typeRoot.

    • so let's say you have the default configuration for typeRoots which would look something like:

      "typeRoots": [
          "./node_modules/@types"
      ]
      
    • let's say you now want to use jasmine as a test framework for your project, so you have your typeRoot folder configured, all you have too do now is execute: npm i @types/jasmine --save-dev

    • after the definition package is installed you just need to configure your 'types' property in 'tsconfig.json' as follows:

      "types": [
           "core-js",
           "jasmine",
           "requirejs",
           "chance"
      ]
      

To conclude, basically you tell the TS compiler the following:

typeRoots: You need to look for typings in these folders. types: In one of the folders provided above, you will find definitions for theses framworks (subfolders).

So using the scenario above, and if we add another root:

"typeRoots": [
    "./node_modules/@types",
    "./custom_definitions"
],
"types": [
    "jasmine",
]

TS will now look for definition files in

./node_modules/@types/jasmine

or

./custom_definitions/jasmine

Hope this helps!


You don't need the types field necessarily. Here is the important part to note from the documentation:

By default all visible “@types” packages are included in your compilation. Packages in node_modules/@types of any enclosing folder are considered visible

So, if you have followed convention or used a tooling set such as npm to download @types packages, you don't need to configure typeRoots or types in your configuration as it will work out of the box with the default folder structure.