gpt4 book ai didi

typescript - 为什么这段代码没有给我一个带有 --noImplicitAny 的错误?

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

即使我启用了 --noImplicitAny 标志,此代码也不会在 TypeScript playground 或 tsc 中向我显示任何错误。为什么不?如果我将 methodName 悬停在 playground 中,它会显示 let methodName: any,所以它似乎得到了那种类型;而且我还没有明确提供它,所以这将是……隐含的。

let methodName;
if (Math.random() < 0.5) {
methodName = "foo";
} else {
methodName = 42;
}
console.log(methodName);

Playground link (不幸的是,您必须手动进入选项并打开该选项, Playground 链接不保留选项)

当它没有给我一个错误时,我有一半希望悬停显示给我 let methodName: string | number(这会让我想:“哇,TypeScript 的类型推断真的很深......”),但它说的是 any

即使只是 let methodName; 本身也不会给我一个错误,但我认为它基本上被忽略了,因为它没有被使用,这就是为什么我有 if/else 上面。

在它前面添加 export 确实给我 Variable 'methodName' implicitly has an 'any' type. 错误我是预期的,所以这可能指向某种原因。

最佳答案

This PR introduces control flow analysis for let and var variables that have no type annotation and either no initial value or an initial value of null or undefined.

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
}

In the example above, x and y implicitly have declared types of any but control flow analysis can determine their actual types at every reference. Therefore, no errors are reported even when the example is compiled with --noImplicitAny.

In time it is possible that control flow analysis will be able to more accurately determine types of references to outer variables from nested functions in some cases, but given that nested functions are first class objects that can be arbitrarily passed around and called, it is effectively impossible to analyze all such scenarios.

Copied from explanation given on this feature by Anders Hejlsberg

关于typescript - 为什么这段代码没有给我一个带有 --noImplicitAny 的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55558220/

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