Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

typescript null/undefined值被推断为什么类型?

环境:

VS Code Version: 1.47.3
tsc Version: 4.0.0-dev.20200727
tsconfig.js: "strict": true,

code:

let x = null; // x 是 any type
let y = x; // x 是 null type(x 在上面是 any type呀?), y 是 null type

x = 1; // x 是 any type
y = 1; // error, y 是 null type

x 到底是什么类型?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

其实 Typescript 中的 any 分为 显式声明隐式推导。开启了 --noImplicitAny 后,当没法推测出变量类型时,Typescript 不再隐式地将变量直接标记为 any ,而是使用了一种改进型的 any 来标记。即:

如果一个变量没有指明类型,且声明时没有初始化或是使用 null 或 undefined 初始化,则这个变量会被标记为 改进型 any 类型,会根据最终的赋值来动态推导其真正的类型

参见官方说明: https://www.typescriptlang.or...

DEMO


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...