let message3;
console.log(typeof((<string>message3))); //Output case1: undefined
console.log(typeof((message3 as string)));//Output case2: undefined
console.log(typeof((message3 as "ABC"))); //Output case3: undefined
console.log(typeof((message3 = "ABC"))); //Output case4: string在上述情况下,为什么情况1-3不起作用,并以字符串形式输出,如case4。
问题1:为什么案例1-3显示“未定义”?
问题2:在情况1-3中,可以进行哪些更改以使输出为“字符串”?
发布于 2018-09-21 18:10:24
TypeScript类型以及所有类型断言都会在运行时被擦除;它们只被编译器用来证明代码的正确性。在转换后的JavaScript中,前三个案例看起来是一样的:
console.log(typeof(message3));而typeof(message3)是未定义的,因为...嗯,您还没有将它定义为任何东西,就像在纯JS中一样:它不知道变量的类型,重要的是它内部的值类型,值是undefined。
https://stackoverflow.com/questions/52441252
复制相似问题