typescript declare third party modules

Viewed 90020

How could I declare a third party module which looks like this:

in third party module:

module.exports = function foo(){
  // do somthing
}

in my code:

import * as foo from 'foo-module'; // Can not find a declaration module for ...
foo();
2 Answers

I had a similar problem. And struggled to add a type definition to my project. Finally, I was able to achieve it using the following steps.

This is some module (just with constants), lets call it some-module - node_modules/some-module/index.js.

'use strict';

exports.__esModule = true;
var APPS = exports.APPS = {
    ona: 'ona',
    tacq: 'tacq',
    inetAcq: 'inetAcq'
};

First I add to tsconfig.json baseUrl and typeRoots

{
  ...
  "compilerOptions": {
    ...
    "baseUrl": "types",
    "typeRoots": ["types"]
  }
  ...
}

Second in my project root I create folder types with same folders structure for the module types/some-module/index.js and place the code:

declare module 'some-module' {
    type Apps =  {
        ona: string;
        tacq: string;
        inetAcq: string;
    };
    let APPS: Apps
}

Finally I can import it in my my-file.ts with typings!

import { APPS } from 'some-module';
Related