Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 953
gilamran Avatar asked Jul 18 '16 19:07

gilamran


People also ask

What is @types in TypeScript?

What is a type in TypeScript. In TypeScript, a type is a convenient way to refer to the different properties and functions that a value has. A value is anything that you can assign to a variable e.g., a number, a string, an array, an object, and a function. See the following value: 'Hello'

How do you declare a variable with two types TypeScript?

TypeScript allows you to define multiple types. The terminology for this is union types and it allows you to define a variable as a string, or a number, or an array, or an object, etc. We can create union types by using the pipe symbol ( | ) between each type.

What is ?: In TypeScript?

What does ?: mean in TypeScript? Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .

How do you handle a union type in TypeScript?

TypeScript Union Type Narrowing To narrow a variable to a specific type, implement a type guard. Use the typeof operator with the variable name and compare it with the type you expect for the variable.


1 Answers

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 and types 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.

Read more in the blog post here.

like image 190
David Sherret Avatar answered Sep 18 '22 13:09

David Sherret