typescript 类型转换中的困惑:为何 as number 仍然是字符串?
在 TypeScript 中,使用 as 进行类型转换可以暂时欺骗编译器,使其认为变量具有不同的类型。然而,这种转换不会在运行时实际发生。
const props = defineProps()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 = 12345n = String(n)console.log(n) // "12345"
登录后复制
在这种情况下,String(n) 会将数字 n 转换为字符串。最终将打印 “12345”,而不是数字。
以上就是TypeScript 类型转换的困惑:为什么使用 as number 仍然是字符串?的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2799739.html