
类型转换中的困惑:为何 as number 仍然是字符串?
在 TypeScript 中,使用 as 进行类型转换可以暂时欺骗编译器,使其认为变量具有不同的类型。然而,这种转换不会在运行时实际发生。
const props = defineProps<{group: number }>()
getDictGroup(props.group)
export const getDictGroup = async (sid: number) => {
const dict = await getDict()
console.info(typeof sid) // number
sid = sid as number
console.info(typeof (sid)) // string
console.info(typeof (sid as number)) // string
}
登录后复制
在此示例中,我们声明 sid 为数字类型,但即使使用了 as number 转换,在运行时它仍然是一个字符串。这是因为 as 转换仅在编译时有效。
真正的类型转换应使用以下语法进行:
let n = 12345 n = String(n) console.log(n) // "12345"
登录后复制
在这种情况下,String(n) 会将数字 n 转换为字符串。最终将打印 “12345”,而不是数字。
以上就是TypeScript 类型转换的困惑:使用 as number 仍然是字符串?的详细内容,更多请关注米云其它相关文章!
