【问题标题】:vscode can't find typeRoots type definitionsvscode 找不到 typeRoots 类型定义
【发布时间】:2018-08-30 16:04:55
【问题描述】:

我试图只有一个文件来包含将在整个应用程序中使用的大部分类型定义,我创建了一个名为 @types 的文件夹和一个导出每个接口的 index.d.ts 文件/输入我想要的。

更新了我的 tsconfig.json 以包含该文件夹:

{
    "compilerOptions": {
        "outDir": "./built",
        "allowJs": true,
        "target": "es5",
        "jsx": "react",
        "allowSyntheticDefaultImports": true,
        "lib": [
            "es2015"
        ],
        "typeRoots": [
            "./@types"
        ],
    },
    "include": [
        "./client/**/*",
        "./@types/**/*"
    ],
    "awesomeTypescriptLoaderOptions": {
        "silent": true,
        "errorsAsWarnings": true
    }
}

即使在代码中(在客户端/...内)我引用 index.d.ts 上存在的接口之一时,vscode 仍会抛出“找不到名称”。

有没有更好的方法来解决这个问题?

@types/index.d.ts 中存在接口定义。

export interface Agent {
    name: string;
...
}

用法:

interface Props extends RouteComponentProps<any> {
    agent?: types.Agent;
}

【问题讨论】:

  • 请将代码(声明和引用)添加到问题中。
  • @MattMcCutchen 定义+用法已添加。

标签: typescript visual-studio-code


【解决方案1】:

由于您使用export 关键字,@types/index.d.ts 被视为一个模块,并且从中访问类型的唯一方法是导入它们。例如,执行以下操作后,您可以参考types.Agent

import * as types from "../path/to/@types/index";

您可能希望删除所有出现的export,以便将@types/index.d.ts 视为全局声明文件,并且您可以将类型简单地称为Agent。或者您可以将类型放在名为 types 的命名空间中,然后引用 types.Agent

typeRoots 编译器选项无关。它告诉编译器在哪里可以找到应加载声明的包,但您的问题不是加载声明(因为@types/index.d.ts 与您的include 匹配)而是导入它们。

【讨论】:

  • 好吧,你明白了。现在我能够理解声明文件是如何工作的了!谢谢。
猜你喜欢
  • 2021-05-05
  • 2018-04-05
  • 1970-01-01
  • 2016-12-20
  • 1970-01-01
  • 2021-01-23
  • 1970-01-01
  • 1970-01-01
  • 2018-07-20
相关资源
最近更新 更多