在TypeScript中,如何使用子模块扩充类型声明

时间:2019-09-10 15:50:56

标签: typescript

我有一个库(这里是高图),该库在软件包@types/highcharts中定义了一些类型定义。

在我要导入的代码中,例如import * as highchartsSolidGauge from 'highcharts/modules/solid-gauge.src.js';

此文件未在定义包中定义。

所以我收到以下错误:

Could not find a declaration file for module 'highcharts/modules/solid-gauge.src.js'. './front-end/node_modules/highcharts/modules/solid-gauge.src.js' implicitly has an 'any' type.
  If the 'highcharts' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/highcharts`

鉴于:   -我不想复制/粘贴@types/highcharts的所有内容   -我不希望(如果可能)通过一个选项,该选项将取消对模块的每次检查

有没有一种方法可以在不更改软件包@types/highcharts的情况下进行编译?

Highcharts仅仅是一个例子,问题本质上是:如何扩展类型定义以声明子模块

1 个答案:

答案 0 :(得分:0)

在项目中创建一个.d.ts文件并添加一个declare module statement

declare module 'highcharts/modules/solid-gauge.src.js';

这是最小的声明。有了它,您从模块导入的任何内容都将具有any类型。

如果您想编写自己的一些类型声明:

declare module 'highcharts/modules/solid-gauge.src.js' {
    export function foo(): string;
}

  

确保TypeScript包含该文件。通常,最简单的方法是在.d.ts的{​​{1}}选项中指定include文件。