ts 类型转换 as number 为何还是string?

作者站长头像
站长
· 阅读数 23

关于ts as number 依旧是string 的问题

const props = defineProps<{group: number }>()

getDictGroup(props.group)

export const getDictGroup = async (sid: number) => {
  const dict = await getDict()
  console.info(typeof sid)
  sid = sid as number
  console.info(typeof (sid))
  console.info(typeof (sid as number))
}

我这里代码已经在每一个步骤已经声明了是 number 但是依旧打印出来时是string

但是如果我使用 parseInt(sid) 又会提示我number 类型的参数不能赋值于 string

所以 类型转换是怎么转换的呢

ts 正确的类型转换

回复
1个回答
avatar
test
2024-06-21

ts 的类型转换 as 是骗编译器的,不会真的在运行时进行类型转换

你要类型转换应该这么写:

let n = 12345
n = String(n)
console.log(n) // "12345"
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容