如何将其他类型导入到 TypeScript .d.ts 模块中

3

我有一个外部模块的自定义 .d.ts 文件,其格式如下:

declare module 'vertices-bounding-box' {
  export default function boundingBox(positions: [number,number,number][]): [number, number]
}

我想使用另一个模块中的类型,而不是 [number,number,number]

import { vec3 } from 'gl-matrix';

declare module 'vertices-bounding-box' {
  export default function boundingBox(positions: vec3[]): [number, number]
}

当我加入vec3的导入语句时,TSC会抱怨:

Invalid module name in augmentation. Module 'vertices-bounding-box' resolves to an untyped
module at '/Users/kevzettler/code/hypeworks/node_modules/vertices-bounding-box/index.js', which cannot be augmented. [2665]
1个回答

5

您刚刚展示了TypeScript中import types最常见的用法:

模块可以导入其他模块中声明的类型。但非模块全局脚本无法访问在模块中声明的类型。这时就需要使用import types。

换句话说,这个语言特性允许您在项目的.d.ts文件的全局作用域中像这样导入外部模块'gl-matrix'的类型:

// ext-module.d.ts, important: don't use ES import statement here
declare module 'vertices-bounding-box' {
  export default function boundingBox(
    positions: Array<import("gl-matrix").vec3>): [number, number]
}

注意:没有 ES 的 import/export 的文件是全局脚本而不是模块。 'vertices-bounding-box' 没有自己的类型,因此需要在一个全局脚本文件中声明,如上所示。 对于那些想要 扩展已经存在的类型,例如来自 DefinitelyTyped / @types 的情况,您将保留顶级 ES 导入。
import { vec3 } from 'gl-matrix';
// ...

在这个文件中,由于模块增强需要一个 module

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接