What exactly are typings?
Essentially, TypeScript introduces static typing to JavaScript. Since JavaScript itself doesn't have predefined type definitions, they need to be created and included in the TypeScript compilation process through additional methods. For instance, a JavaScript library may have a function defined as:
export function createPerson(name, age, initScore) { ... }
However, within the statically typed environment of TypeScript, it would be more beneficial for developers to have something like this:
interface Person {
name: string,
age: number,
score: number
}
export function createPerson(name: string, age: number, initScore?: number): Person;
The purpose of type declarations, commonly referred to as typings, type definitions, or simply types, is to provide these details over implementations, thereby identifying API misuses even across different libraries. These declarations typically exist in files with a .d.ts
extension and can be generated from .ts
files using the compiler. When programs were not originally written in TypeScript, these declarations are usually crafted manually.
Your confusion is understandable given that there have been multiple approaches to installing and managing TypeScript declarations over time. Currently, there is an official (and thus recommended) method for acquiring and utilizing declaration files, documented here:
In TypeScript 2.0, consuming declaration files has become much simpler in terms of acquiring, using, and locating them. This page provides precise instructions on how to accomplish all three tasks
[...]
Obtaining type declarations in TypeScript 2.0 and above no longer requires any tools other than npm.
For example, obtaining declarations for Angular is as easy as adding this dependency to your project:
npm install --save @types/angular
Packages in the @types
namespace will automatically be recognized by the compiler for acquiring type declarations. Additionally, if these declarations are already incorporated in the npm package, you only need to install that package without any extra steps (an example of such a package is redux). For further information, refer to the documentation on tsconfig.json. There is also a dedicated section on creating your own declaration files, which is highly recommended for developers looking to include type declarations in their own libraries.