打字稿声明第三方模块

typescript declare third party modules

如何声明第三方模块,如下所示:

在第三方模块中:

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

在我的代码中:

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

查看 documentation on working with 3rd party modules

如何编写声明在很大程度上取决于模块的编写方式和导出的内容。

您给出的示例是 CommonJS 模块 (module.exports = ...),它实际上不是有效的 ES6 模块,因为 ES6 无法将函数 导出为模块 (它只能导出函数成员或 default 函数)。

TypeScript 2.7+ 更新

添加 esModuleInterop compiler option 后,您不再需要为具有非 ES6 兼容导出的 CommonJS 模块使用下面显示的 "namespace hack"。

首先,确保您已在 tsconfig.json 中启用 esModuleInterop(现在默认包含在 tsc --init 中):

{
  "compilerOptions" {
    ...
    "esModuleInterop": true,
    ...
   }
}

像这样在 .d.ts 文件中声明您的 foo-example

declare module "foo-module" {
  function foo(): void; 
  export = foo;
}

现在您可以将其导入为您想要的命名空间:

import * as foo from "foo-module";
foo();

或作为默认导入:

import foo from "foo-module";
foo();

旧的解决方法

您可以像这样在 .d.ts 文件中声明您的 foo-example

declare module "foo-module" {
  function foo(): void; 
  namespace foo { } // This is a hack to allow ES6 wildcard imports
  export = foo;
}

然后按你想要的方式导入:

import * as foo from "foo-module";
foo();

或者像这样:

import foo = require("foo-module");
foo();

documentation has a good resource on declaration files and some templates for various kinds of declaration files.

我遇到了类似的问题。并努力将类型定义添加到我的项目中。终于想到了。

这是一些模块(只有常量),我们称它为 some-module - node_modules/some-module/index.js.

'use strict';

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

首先我添加到 tsconfig.json baseUrltypeRoots

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

其次,在我的项目根目录中,我为模块 types/some-module/index.js 创建了具有相同文件夹结构的文件夹 types 并放置代码:

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

我终于可以通过打字将其导入我的 my-file.ts

import { APPS } from 'some-module';