【问题标题】:TS compilation - "noImplicitAny" doesn't workTS 编译 - “noImplicitAny”不起作用
【发布时间】:2017-07-27 12:59:48
【问题描述】:

我有密码

let z;
z = 50;
z = 'z';

而我的 tsconfig.json 是:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "sourceMap": false,
    "noEmitOnError": true,
    "strict": true,
    "noImplicitAny": true
  }
}

但是编译成js没有异常是什么鬼?

最好的问候, 克罗瓦

【问题讨论】:

    标签: javascript typescript tsconfig


    【解决方案1】:

    因为z 永远不会输入为anyz 的类型只是根据您分配给它的内容推断出来的。

    来自release notes

    在 TypeScript 2.1 中,TypeScript 将不只是选择任何一个,而是 根据您稍后最终分配的内容推断类型。

    示例:

    let x;
    
    // You can still assign anything you want to 'x'.
    x = () => 42;
    
    // After that last assignment, TypeScript 2.1 knows that 'x' has type '() => number'.
    let y = x();
    
    // Thanks to that, it will now tell you that you can't add a number to a function!
    console.log(x + y);
    //          ~~~~~
    // Error! Operator '+' cannot be applied to types '() => number' and 'number'.
    
    // TypeScript still allows you to assign anything you want to 'x'.
    x = "Hello world!";
    
    // But now it also knows that 'x' is a 'string'!
    x.toLowerCase();
    

    所以在你的情况下:

    let z;
    z = 50;
    let y = z * 10; // `z` is number here. No error
    z = 'z';
    z.replace("z", "")// `z` is string here. No error
    

    【讨论】:

    • 是否有禁止这种行为的标志?
    • 据我所知没有。
    【解决方案2】:

    noImplicitAny 字面意思是:

    如果 TypeScript 在无法推断出一个 输入

    在上述情况下,您的代码编译器的任何时候都可以轻松推断出z 的类型。因此它可以检查您在z 上调用的适当方法/道具是否被允许。

    【讨论】:

    • 在什么情况下 --noImplicitAny 至少会做点什么?
    猜你喜欢
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2011-10-29
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-29
    相关资源
    最近更新 更多