noImplicitAny编译器标志的范围是什么

时间:2017-05-20 08:20:54

标签: typescript

TypeScript文档将noImplicitAny编译器标志记录到

  

使用隐含的any类型提高表达式和声明的错误。

所以在下面的代码中:

let x;            // x is of implicitly of type `any`, but no error

function foo(y) { // error: parameter 'y' implicitly has an 'any' type. 
    let z;        // z is of implicitly of type `any`, but no error
}

不应该将xz标记为隐式输入any吗?

1 个答案:

答案 0 :(得分:2)

这实际上是由于2.1版本中的修复。在此之前,您的代码会抛出错误。

来自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();

因此,在您的情况下,TypeScript实际上会根据您分配给它的内容推断类型:

function foo(y) { 
    let z;
    z = "somestring";
    z.toUpperCase(); // z is string now. No error;
    z = 10;
    z.toUpperCase(); // z is number now; Error
}