How to create typings for libraries in Typescript?

May 20, 2017

If something I have to recognize is that #Typescript allows to have control in #Javascript and that is also thanks to the typings (tsd), but some libraries aren’t typings ready, like my library rdjs and I need to create them.

Creating the typings

To create our library typings, we have to have our library installed using npm and within our project, we create a directory called typings and in another one with the name of the library that we want in my case rdjs

npm install rdjs  typings/index.d.ts typings/rdjs/index.dt.ts

Typescript interprets the * .d.ts files as declaration files and these describe the methods the library exposes without implementing them.

In the typings directory, we have an index.d.ts that will contain a reference to each of our declaration files.

In this case, typings /index.d.ts will contain a reference to the rdjs/index.d.ts file.

/// <reference path = "rdjs / index.d.ts" />

Defining typings

All definitions of the typings will be done in typings/rdjs/index.d.ts, the first thing we have to do is create an ambient module which are declarations of the type .

We declare a module with the same name as the npm module in my case rdjs.

declare module 'rdjs' { }

Then we define an interface with the methods and their signature that we want to use, in this case, I have put the different methods that expose get, post, put and delete and make an export of the object rdjs is an object, our module will export a variable const implementing the interface that contains our specifications.

declare module 'rdjs'{  interface rdjs {  get(url: string, params: any): Promise<any>  post(url: string, params: any): Promise<any>  put(url: string, params: any): Promise<any>  delete(url: string, params: any): Promise<any>  }  const rdjs: rdjs export = rdjs }

Now we have the methods that I will use in my application and I can see how visual studio code autocomplete the code, specify the signature that needs that method and its parameters and the compiler alerts me that I’m not sending the expected type.

Now we have our ideal can autocomplete and also show the signature of the methods or visually alert us that we are not passing the parameters specified in the interface and the compiler alerts us that I am not sent sending the expected parameters.

scroller.ts (22,9): error TS2346: Supplied parameters do not match any signature of the target.

The complete code or you can see the complete code in Github


Originally published at danywalls.com on May 20, 2017.

Dany Paredes

Hi, I'm Dany Paredes, few years ago I was working with .NET, but in my last years I have been focusing in Javascript using Vue , Angular or React. You can read more in Twitter or Github.