【问题标题】:TypeOf and AssertionTypeOf 和断言
【发布时间】:2019-02-25 17:13:13
【问题描述】:
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:在case 1-3中可以做哪些改变来输出“string”?

【问题讨论】:

  • console.log(typeof 42); // 预期输出:“数字”MDM typeof

标签: typescript ecmascript-6 assertion typeof


【解决方案1】:

TypeScript 类型以及所有类型断言在运行时被擦除;它们仅被编译器用来证明您的代码是正确的。在转译的 JavaScript 中,前三种情况看起来是一样的:

console.log(typeof(message3));

typeof(message3) 是未定义的,因为...好吧,您还没有将它定义为任何东西,就像在纯 JS 中一样:它不知道变量的类型,重要的是里面的value的类型,value是undefined

【讨论】:

  • 回答问题 1。对于问题 2 - 是否有可能在运行时使用断言使其成为字符串?
  • 嗯,对于问题 2,因为现在被问到的答案是“无能为力”。您想通过这种方式实现什么目标?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-28
  • 1970-01-01
  • 2015-07-17
  • 2019-04-29
  • 1970-01-01
  • 2019-06-21
  • 1970-01-01
相关资源
最近更新 更多