How should I use @types with TypeScript 2
So far we are used to tsd or (The better version of it) typings
But now that TypeScript 2 offers the new @types
feature, how should I convert my current project to work with @types?
I have tsd.json (typings.json is some cases) with all the dependencies, what are the steps to do the move to TypeScript 2?
What are the new best practices? Does @types support specific versions?
It's very simple. Just install the definitions that you need via npm.
For example if you need lodash you can do:
npm install --save @types/lodash
Once it's installed you can use it right away in your project. Typescript will resolve the typings for the installed @types package from the node_modules/@types folder by default. There's no need for a tsd.json or typings.json file anymore.
Additional points:
- The major and minor version of the @types package in npm should correspond with the package version.
- You can search for types here: http://microsoft.github.io/TypeSearch/
- Read about
typeRoots
andtypes
here. Specifically pay attention to these two points:- If
typeRoots
is specified in tsconfig.json, then only specified folders will be used for the type roots. That will exclude ./npm_modules/@types/ unless you specify it. - If
types
is specified in tsconfig.json, then only the packages specified will be included.
- If
Read more in the blog post here.
Typescript 2.0 gets rid of previous Typings system.
Now Typescript 2.0 should by default look into ./node_modules/@types
and get types that you installed as the separate node modules, e.g. npm install --save @types/react
(as mentioned by @David Sherret)
There is a bug in the current version Typescript 2.0 beta, which does not load new types. Manually via cmd new tsc compiles files, but there is no IntelliSense support in VS 2015, and no errors are showed while a .ts file is in edit mode.
To resolve it modify tsconfig.json
with the similar settings:
{
"compilerOptions": {
// ... other config rows
"typeRoots": [ "node_modules/@types/" ],
"types": [ "jquery", "react", "react-dom", /*... your other types */ ],
}
}
For me manual "types"
declaration helped resolved this issue, for other guys "typeRoots"
helped. Hopefully it will save developer's hours.
It looks like they are all just npm packages, you can find all the supported ones here.
tsc will pick up any types in the node_modules folder.
You can move the dependencies you have in typings.json in package.json (provided you change the names too ofcourse).
You can read more about that here.
how should I convert my current project to work with @types
I definitely recommend holding on for a bit longer.
e.g. issues are still getting fixed ... just 4 hours ago : https://github.com/Microsoft/TypeScript/issues/9725#issuecomment-233469422