【问题标题】:Manually add TypeScript typings for npm utility为 npm 实用程序手动添加 TypeScript 类型
【发布时间】:2017-05-27 00:38:19
【问题描述】:

我正在现有的 JS 项目中设置 TypeScript,我正在尝试弄清楚如何将类型添加到无类型的 npm 模块,因为我知道它会出现。

这一行

import X from 'foo';

Cannot find module 'foo' 出错

typings/modules 我有一个foo 文件夹,其中包含一个 index.d.ts 文件

declare module foo {
    export default class XXX{

    }
}

在父 typings/index.d.ts 我已经添加

/// <reference path="modules/foo/index.d.ts" />

但还是一无所获。

我的 tsconfig.json 文件是这样的

{
    "compilerOptions": {
        "target": "esnext",
        "baseUrl": "./src",
        "jsx": "react",
        "allowSyntheticDefaultImports": true,
        "allowJs": true,
        "moduleResolution": "node",
        "module": "es2015",
        "experimentalDecorators": true,
        "lib": ["es2015", "dom"],
        "typeRoots" : ["./typings/modules", "./node_modules/@types"]
    },
    "include": [
        "./src/**/*.ts",
        "./src/**/*.tsx"
    ]
}

【问题讨论】:

    标签: typescript


    【解决方案1】:

    你必须用引号声明你的模块:

    declare module "foo" {
        export default class XXX{
    
        }
    }
    

    看起来很疯狂?不带引号声明的模块实际上类似于命名空间。因此,您实际上并没有在代码中声明模块。

    来自documentation

    “内部模块”现在是“命名空间”。 “外部模块”现在 简单的“模块”,以符合 ECMAScript 2015 的术语, (即模块 X { 相当于现在首选的命名空间 X {)。

    另见:What's the difference between declaring a module in TypeScript with quotes vs without?

    【讨论】:

    • 多谢。一旦我不接受并接受,将立即进行测试。
    猜你喜欢
    • 2023-02-03
    • 1970-01-01
    • 2022-12-01
    • 2020-01-03
    • 2020-10-23
    • 2020-05-23
    • 2021-08-03
    • 2017-08-15
    • 1970-01-01
    相关资源
    最近更新 更多