代码之家  ›  专栏  ›  技术社区  ›  marcoseu

设置“noimplicitany”时,typescript将忽略“typeroots”

  •  7
  • marcoseu  · 技术社区  · 6 年前

    我通常设置我的 tsconfig.json 具有 strict 设置为 true . 这意味着 noImplicitAny 也设置为 . 然而,何时 严格的 设置了,typescript似乎忽略了我的 typeRoots 本地创建的条目 *.d.ts 文件。这是一个样品 TSOCONT.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/**/*" ]
    }
    

    我可以将以下内容添加到 TSOCONT.JSON 在上面,它将起作用:

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

    下面是我创建的一个示例项目,用于说明此问题:

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

    知道为什么会这样吗?

    1 回复  |  直到 6 年前
        1
  •  4
  •   Titian Cernicova-Dragomir    6 年前

    noImplicitAny: false 并不能真正解决问题,只是忽略了它。 template 将隐式键入为 any 因为找不到类型。您不会得到错误,但也不会得到类型安全性。

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

    最简单的解决方案是移除 types 元素从 tsconfig.json . 此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/**/*" ]
    }