noImplicitAny不工作的Typescript

问题描述 投票:4回答:1

在我的根文件夹中,我有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,任何人都知道什么可能是个问题?

typescript visual-studio-code tsc tsconfig
1个回答
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
}

描述了它的工作原理。

© www.soinside.com 2019 - 2024. All rights reserved.