typescript declare third party modules

后端 未结 3 1383
盖世英雄少女心
盖世英雄少女心 2020-12-15 03:21

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

in third party module:

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

3条回答
  •  臣服心动
    2020-12-15 04:24

    I had a similar problem. And struggled to add type definition to my project. Finally I made it thought.

    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';
    

提交回复
热议问题