gpt4 book ai didi

typescript - 推断出什么类型的空/未定义?

转载 作者:行者123 更新时间:2023-12-04 09:18:59 25 4
gpt4 key购买 nike

环境:

VS Code Version: 1.47.3
tsc Version: 4.0.0-dev.20200727
tsconfig.js: "strict": true,
代码:
let x = null; // x is any type
let y = x; // x is null type(why? x is any type on top), y is null type

x = 1; // x is any type
y = 1; // error, y is null type
这是正常的吗?推断出什么类型的 x?我很迷惑

最佳答案

这与此有关 PR它为隐式类型为 any 的变量引入了控制流分析 (CFA)

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.


此分析仅适用于

[...] let and var variables that have no type annotation and either no initial value or an initial value of null or undefined.


因此,让我们看看您的示例中会发生什么:
// x is implicitly any, with null assigned, so this new CFA analysis kicks in 
let x = null;
// for x, based on the assignment on the previous line, x is known to be null
// y typed based on the type of x, so y has type null.
// No special CFA is triggered for y since it is not assigned the null literal value
let y = x;

// x can be assigned any type, since it has no type annotation, so number is fine
x = 1;

// y was actually given a type when it was declared, the null type, so you can't assign number
y = 1;

// x is now number based on previous assignments
x.toExponential()
x是赋值的目标,它的行为为 any ,允许为其分配任何类型。当它在表达式中使用时,它的类型将根据之前的赋值来确定。

关于typescript - 推断出什么类型的空/未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63128761/

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