环境:
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
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
andvar
variables that have no type annotation and either no initial value or an initial value ofnull
orundefined
.
让我们看看您的示例中会发生什么:
// 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 - 推断出什么类型的 null/undefined?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63128761/