简体   繁体   English

打字稿是否仅在类型声明后为变量赋值时才返回变量类型?

[英]Does typescript return type of variable only when it is assigned some value after type declaration?

In type script, is it possible to get the type of a variable before assigning any value to it?在类型脚本中,是否可以在为其分配任何值之前获取变量的类型?

let a: number;
console.log(typeof a);

returns undefined返回undefined

where as然而

let a: number;
a = 10;
console.log(typeof a);

returns number返回number

No.不。

Types are erased in TypeScript.类型在 TypeScript 中被擦除。 They don't exist at runtime.它们在运行时不存在。

In fact, TypeScript has no runtime semantics at all .事实上,TypeScript 根本没有运行时语义 TypeScript cannot possibly change the result of the code from what the result would be in plain ECMAScript. TypeScript不可能改变代码的结果,而不是普通 ECMAScript 的结果。

What you are using in your code snippet is the ECMAScript typeof operator, it has nothing to do with TypeScript, and it doesn't know anything about TypeScript.您在代码片段中使用的是ECMAScript typeof运算符,它与 TypeScript 无关,并且对 TypeScript 一无所知。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM