typescript - 推断出什么类型的 null/undefined?

标签 typescript typescript-typings

环境:

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 - 推断出什么类型的 null/undefined?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63128761/

相关文章:

reactjs - React-Native/Typescript - 未定义不是一个对象(评估'react_1.default.Component)

typescript - 打字 : SyntaxError: Unexpected token =>

typescript - 根据 typescript 中的构造函数参数重载类属性

javascript - 在 Typescript 中创建/修复 node-json2html 的声明文件

javascript - ionic2 - 滚动触发

typescript - 有没有一种方法可以使用泛型参数导入类型?

html - Angular 2 - 动画过渡不起作用

javascript - Angular 1 TypeScript 项目中的依赖注入(inject)

node.js - 我应该在 package.json 中为 'types' 字段使用什么值?

javascript - TypeScript 可更新和枚举引用