Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom "typings" in typescript 2.0 / 3.0

According to this article typings system for typescript 2.0 has changed and so it is not clear how to attach custom typings now. Should I always create NPM package for that?

Thank you in advance!

like image 247
Lu4 Avatar asked Aug 16 '16 10:08

Lu4


People also ask

Where does TypeScript look for Typings?

The . d. ts file is usually placed adjacent to the . ts file, it is providing the typings for.

What is Typings in TypeScript?

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.


1 Answers

You can create local custom typings just for your project, where you can declare types for JS libraries. For that, you need to:

  1. Create directory structure to keep your type declaration files so that your directory structure looks similar to this:

     .  ├── custom_typings  │   └── some-js-lib  │       └── index.d.ts  └── tsconfig.json 
  2. In the index.d.ts file, add a declaration for your JS library:

     declare module 'some-js-lib' {    export function hello(world: string): void  } 
  3. (Optional: skip if you have TypeScript >= 4.x) Add a reference to this type declaration in the compilerOptions section of your tsconfig.json:

     {    "compilerOptions": {      ...      "typeRoots": ["./node_modules/@types", "./custom_typings"]    },    ...  } 
  4. Use the declared module in your code:

     import { hello } from 'some-js-lib'   hello('world!') 
like image 172
MisterMetaphor Avatar answered Sep 24 '22 06:09

MisterMetaphor