gpt4 book ai didi

设置 `typeRoots` 时 typescript 忽略 `noImplicitAny`

转载 作者:搜寻专家 更新时间:2023-10-30 20:36:34 24 4
gpt4 key购买 nike

我通常设置我的 tsconfig.json 并将 strict 设置为 true。这意味着 noImplicitAny 也设置为 true。但是,当设置了 strict 时,typescript 似乎忽略了我在本地创建的 *.d.ts 文件的 typeRoots 条目。这是我使用的示例 tsconfig.json:

{
"compilerOptions": {
"declaration": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [ "es2017" ],
"module": "CommonJS",
"noImplicitReturns": true,
"outDir": "lib",
"removeComments": true,
"sourceMap": true,
"strict": true,
"target": "es2017",
"typeRoots": [ "./typings", "./node_modules/@types" ],
"types": [ "node" ],
},
"compileOnSave": true,
"include": [ "./src/**/*" ]
}

我可以将以下内容添加到上面的 tsconfig.json 中,它会起作用:

{
"compilerOptions": {
...
"noImplicitAny": false,
...
}
}

这是我创建的一个示例项目来说明这个问题:

https://github.com/marcoslin/tstyping-test

知道为什么会这样吗?

最佳答案

noImplicitAny: false 并没有真正解决问题,它只是忽略了它。 template 将被隐式键入为 any,因为未找到任何类型。你没有得到任何错误,但也没有类型安全。

真正的问题是您指定了 "types": [ "node"], 这意味着只有节点模块的类型来自 typeRoots。参见 docs .

最简单的解决方案是从 tsconfig.json 中删除 types 元素。这个 tsconfig 没有给出任何错误:

{
"compilerOptions": {
"declaration": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [ "es2017" ],
"module": "CommonJS",
"noImplicitReturns": true,
"outDir": "lib",
"removeComments": true,
"sourceMap": true,
"strict": true,
"target": "es2017",
"typeRoots": [ "./typings", "./node_modules/@types" ]
},
"compileOnSave": true,
"include": [ "./src/**/*" ]
}

关于设置 `typeRoots` 时 typescript 忽略 `noImplicitAny`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54289791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com