【问题标题】:How to import other types in to a typescript .d.ts module如何将其他类型导入打字稿 .d.ts 模块
【发布时间】:2021-02-03 18:12:07
【问题描述】:

我有一个自定义的.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]

【问题讨论】:

    标签: typescript webpack typescript-typings gl-matrix


    【解决方案1】:

    您刚刚在 TypeScript 中展示了 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' 没有自己的类型,因此需要在全局脚本文件中声明这些类型,如上所示。 对于您想要 extend already existing types 喜欢来自definitelyTyped / @types 的情况,您将保留顶级 ES 导入

    import { vec3 } from 'gl-matrix';
    // ...
    

    在这个文件中,因为模块扩充需要一个模块

    【讨论】:

      猜你喜欢
      • 2018-01-10
      • 2021-09-14
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 2019-11-17
      • 2020-04-29
      • 1970-01-01
      • 2018-04-27
      相关资源
      最近更新 更多