You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何TypeScript中标注为number的变量typeof返回string?

为什么类型断言后typeof仍返回string?

这是因为TypeScript的类型断言(as语法)只是编译阶段的类型提示,完全不会改变运行时变量的实际类型:

  • 你用quantity as unknown as number,只是告诉TypeScript编译器“把这个变量当成number类型来做类型检查”,但在代码运行时,numericQuantity的本质还是原来的字符串'10',所以typeof检测出来还是string。
  • 类型断言不是类型转换,它没有任何运行时的逻辑,不会帮你把字符串转成数字。

如果要真正得到数字类型的变量,得用运行时的转换方法,比如:

let quantity: string = '10';
// 用Number()做实际的类型转换
let numericQuantity: number = Number(quantity);

console.log(typeof quantity);  // string
console.log(typeof numericQuantity);  // number

其他可行的转换方式还有parseInt(quantity, 10)、+quantity,这些才是真正在运行时把字符串转成数字的操作。

内容的提问来源于stack exchange,提问作者R0_0107

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 06:12:02