Typescript – What are Typings in Typescript

typescripttypescript-typings

I am new to Angular2 and I'm enjoying it so far but there is one problem: Typings. I can't figure out how to use them and what exactly they are. Some places say to use typings, others say to use npm to install definitions.

I'm confused!!

Best Answer

JavaScript is untyped, meaning that we can pass around and use data, objects and functions with no constraints. We can write code that calls methods that don't exist on an object, or reference variables that we don't have. These kinds of mistakes can be hard to discover when you are writing code, and it can lead to unstable and buggy code. Doing big changes of your code can become difficult and risky as you don't immediately see if some changes conflicts with the rest of the code somewhere else.

TypeScript is mainly about adding types to JavaScript. That means that TypeScript requires you to accurately describe the format of your objects and your data. When you do that, that means that the compiler can investigate your code and discover errors. It can see that you are trying to call a function with the wrong kinds of arguments, or reference a variable that is not accessible in the current scope.

When you write TypeScript yourself, this formal description of the code is part of the code itself.

However, when you use external libraries like jQuery or moment.js, there are no information of the types in that code. So in order to use it with TypeScript, you also have to get files that describe the types of that code. These are the type declaration files, most often with the file extension name .d.ts. Fortunately people have written those kinds of type declaration files for most common javascript libraries out there.

Typings was just a tool to install those files. It is now best practice to just use npm.

When you have installed those files, which basically only means downloading them and placing them in your project, the TypeScript compiler will understand* that external code and you will be able to use those libraries. Otherwise you would only get errors everywhere.

* Depending on how you have set up your project and configured it, you might have to configure typescript to look for those files specifically, or it might just work without any configuration from your part.