Getting started with TypeScript type definitions

Jonathan Harrison
2 min readNov 13, 2017

--

For a new side project I am just beginning to work on, I plan on using the npm module themeparks in an Express app written in TypeScript. themeparks currently doesn’t have a type definition, but in order to use it with TypeScript I will need one.

Now I could have just done the bare minimum as per the TypeScript documentation:

declare module "themeparks"

However I know that I am going to be using themeparks extensively so I thought investing some time upfront to create a complete type definition would pay returns later. Also since I hadn’t written a type definition before, I thought it would be fun to give it a go.

After a couple of days work (on and off) and some initial reading around, I completed it (or one that would be good enough for now) which you can find here.

For anyone who wants to know how to get started, here are the tools I used.

dts-gen

dts-gen is a command line tool written by Microsoft that generates a TypeScript definition file from any JavaScript object e.g an NPM module or a file. It can also generate the folder structure and files required if you wanted to contribute to DefinitelyTyped.

For example to create a starting point for the themeparks type definition, the pre-requisites are:

  • Install dts-gen globally.
  • Install themeparks globally.
  • Create a folder structure: myproject >types > themeparks (Note: if you don’t have this folder structure, then dts-gen will crash with “Error: ENOENT: no such file or directory”)

Then run the following with myproject being the current working directory:

dts-gen -m themeparks -d themeparks -o

This is great as it means you don’t have to start completely from scratch; the only downside is that as dts-gen works by examining the objects at runtime, you will get a lot of any’s.

dtslint

dtslint is a linter for type definition files (built on top of tslint) by Microsoft. Like any other linter, dtslint tests a type definition for style and correctness and if you used dts-gen, the majority of the setup is already done for you.

Just install dtslint globally, write some tests and then run:

dtslint types/themeparks

You should see some linting errors. On the other hand, you may get some errors such as “Expected strictFunctionTypes: true”; to solve these just add the property to the tsconfig.json.

Other resources

That’s all the tools but if you want to find out more about type definitions then have at look the DefinitelyTyped documentation which details common mistakes and how to publish a definition.

Also the TypeScript documentation provides a lot of declaration examples and Do’s and Dont’s, which come in handy when developing your type definition.

--

--

Jonathan Harrison
Jonathan Harrison

Written by Jonathan Harrison

Principal Software Engineer @ Tripadvisor. Formerly at Spotify, Altitude Angel and Microsoft. All opinions are my own.

Responses (2)