noImplicitAny不工作的Typescript

时间:2018-03-02 15:22:43

标签: typescript visual-studio-code tsc tsconfig

在我的根文件夹中,我有tsconfig.json文件,如下所示:

{
  "compilerOptions": {
    /* Basic Options */
    "target": "es2015", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
    "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "lib": [
      "es2017",
      "dom"
    ],                             /* Specify library files to be included in the compilation. */
    "declaration": false,                   /* Generates corresponding '.d.ts' file. */
    "outDir": "./dist", /* Redirect output structure to the directory. */
    "rootDir": "./src",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    /* Strict Type-Checking Options */
    "strict": true, /* Enable all strict type-checking options. */
    "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    "strictNullChecks": true,              /* Enable strict null checks. */
    "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    /* Additional Checks */
    "noUnusedLocals": true,                /* Report errors on unused locals. */
    "moduleResolution": "node", 
    "typeRoots": [
      "node_modules/@types"
    ],                       /* List of folders to include type definitions from. */
    "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    "emitDecoratorMetadata": true         /* Enables experimental support for emitting type metadata for decorators. */
  }
}

在我的src文件中,我有文件,我有这样的东西:

export class CompareDatesLogic implements ICRUD {

    public create() {
        let test;

        test = 'aaaa';
        return {
            name: test,
        };
    }
}

但是Visal Code没有检测到noImplicitAny,任何人都知道什么可能是个问题?

1 个答案:

答案 0 :(得分:3)

查看https://github.com/Microsoft/TypeScript/issues/18679 /和https://github.com/Microsoft/TypeScript/pull/11263了解更多详情,

简而言之,TS编译的新功能允许控制流分析确定最初未分配的值的类型。

在你的代码中

let test; //no types defined test = 'aaa' //assigned string

并且在这两次执行之间没有任何变异类型test,tsc auto通过分析代码来推断test:string

我借用了详细的例子:

function f(cond: boolean) {
    let x;
    if (cond) {
        x = "hello";
        x;  // string
    }
    else {
        x = 123;
        x;  // number
    }
    return x;  // string | number
}

function g(cond: boolean) {
    let y = null;
    if (cond) {
        y = "hello";
    }
    return y;  // string | null
}

描述了它是如何工作的。