
ts 类型转换为何失效?
在 TypeScript 中,as 运算符用于类型转换,但在某些情况下,as number 转换可能无法将字符串转换为数字。
考虑以下代码:
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))
}
登录后复制
尽管代码中声明了 sid 是 number 类型,但输出结果却是字符串。这是因为 as 运算符只是欺骗编译器,而不会在运行时实际进行类型转换。
正确的类型转换方式应该如下:
let n = 12345 n = String(n) console.log(n) // "12345"
登录后复制
在这个示例中,String() 函数将数字 12345 转换为字符串 “12345”。
以上就是TypeScript 中的 as 类型转换为何失效?的详细内容,更多请关注米云其它相关文章!
