打字稿:严格检查"任何"

时间:2017-07-10 02:52:38

标签: typescript types any tsconfig

我的Typescript配置允许编译以下代码:

const thing : any = 123
const name : string = thing

显然,name实际上不是string,但我将其声明为any这一事实使我的类型检查员忽略它。

在我为对象提供正确的类型之前,如何配置我的tsconfig.json 给我一个错误?

我目前的配置:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6",
        "noEmitOnError": true,
        "noImplicitAny": true,
        "noImplicitReturns": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "strictNullChecks": true,
        "moduleResolution": "node",
        "sourceMap": true,
        "outDir": "dist",
        "baseUrl": ".",
        "paths": {
            "*": [
                "node_modules/*",
                "src/types/*"
            ]
        }
    },
    "include": [
        "src/**/*.ts"

    ]
}

2 个答案:

答案 0 :(得分:1)

  

但事实上我将其声明为任何使我的typechecker忽略它。

这是设计的。通过说明any明确地要求类型检查器忽略它,这就是它的作用

答案 1 :(得分:1)

类型any通过设计禁用类型检查器。从TypeScript 3.0开始,还有另一种称为unknown的类型,它基本上是any的严格版本。

const thing: unknown = 123;
const name: string = thing; // <- error TS2322: Type 'unknown' is not assignable to type 'string'.

您可以在release notes of TypeScript 3.0中找到有关它的更多信息。 目前(发布后约两年),该类型尚未列为basic types on the website之一。但是,有一个beta for a new version of the website也列出了unknown