gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:10:34 25 4
gpt4 key购买 nike

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

Raise error on expressions and declarations with an implied any type.

所以在下面的代码中:

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

最佳答案

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

来自release notes :

With TypeScript 2.1, instead of just choosing any, TypeScript will infer types based on what you end up assigning later on.

Example:

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
}

关于typescript - noImplicitAny 编译器标志的范围是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44083580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com