TS编译 - "noImplicitAny"不起作用

Cro*_*ova 5 javascript typescript tsconfig

我有代码

let z;
z = 50;
z = 'z';
Run Code Online (Sandbox Code Playgroud)

我的tsconfig.json是:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "sourceMap": false,
    "noEmitOnError": true,
    "strict": true,
    "noImplicitAny": true
  }
}
Run Code Online (Sandbox Code Playgroud)

但到底有没有例外,那就是编译到js没有例外?

最诚挚的问候,克罗瓦

Sar*_*ana 5

因为z永远不会输入any.z根据您分配给它的内容简单地推断出类型.

发行说明:

使用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();
Run Code Online (Sandbox Code Playgroud)

所以在你的情况下:

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
Run Code Online (Sandbox Code Playgroud)


Ami*_*mid 1

noImplicitAny字面意思是:

如果 TypeScript 在无法推断类型时使用“any”,则会触发错误

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

  • 在什么情况下 --noImplicitAny 至少会做一些事情? (2认同)