How to consume npm modules from typescript?

[2018/12] New, up-to-date, answer to this question I asked in 2016, which stills shows a lot of activity despite having outdated answers.

Long story short, TypeScript requires type informations about your package’s code (a.k.a. “type declaration files” a.k.a. “typings”) and rightfully tells you that you would otherwise be losing the whole point of TypeScript. There are several solutions to provide them or opt out of them, listed here in order of best practice:


Solution 0: the module already provides the typings. If its package.json contains a line like this:

"typings": "dist/index.d.ts",

it is already TypeScript-enabled. It’s most likely not the case if you are reading this page, so let’s continue…


Solution 1: use community-contributed typings from DefinitelyTyped. For a module “foo”, try this:

npm add -D @types/foo

if it works, jackpot! You now have the typings and can use your module. If npm complains that it can’t find the module @types/foo, let’s continue…


Solution 2: provide custom typings about this module. (with an option to do zero effort)

  1. Create a folder named “typings-custom” at the root of your project
  2. Reference the content of this folder in your tsconfig.json:
"include": [
    "./typings-custom/**/*.ts"
]
  1. Create a file with this exact name: foo.d.ts [foo = the name of the module] with the content:
declare module 'foo'

Your TypeScript code should now compile, albeit with NO type information (TypeScript consider the foo module of type “any”).

You can also attempt to write the type information yourself, looking at the official doc and/or at examples from DefinitelyTyped. If you do, think of contributing your typings either directly into the module (solution 0, if the module author accepts) or into DefinitelyTyped (solution 1)

Leave a Comment