医院网站建设联系方式营销型网站建设公司排名
web/
2025/10/3 14:49:43/
文章来源:
医院网站建设联系方式,营销型网站建设公司排名,手机net网站开发,重庆最专业的房产网站建设Typescript允许你覆盖它的判断#xff0c;并且能以任何你想要的方式分析它#xff0c;这种机制被称为类型断言。
类型断言的两种方式#xff1a;
1.as关键字
interface SquareConfig {color?: string;width?: number;
}function createSquare(config: SquareConfig) {/…Typescript允许你覆盖它的判断并且能以任何你想要的方式分析它这种机制被称为类型断言。
类型断言的两种方式
1.as关键字
interface SquareConfig {color?: string;width?: number;
}function createSquare(config: SquareConfig) {// ...
}let mySquare createSquare({ width: 100, opacity: 0.5 } as SquareConfig);
2.尖括号
let someValue: any this is a string
let strLength: number (stringsomeValue).length
一般情况建议使用as关键字来断言尖括号断言在jsx中会有歧义因此建议统一使用as。
注意
类型断言只能够欺骗typescript编译器无法避免运行时的错误。
类型断言和类型转换对比
类型断言只会影响typescript编译时的类型类型断言在编译结果中会被删除。上述代码经过typescript编译后会变成
let someValue this is a string
let strLength someValue.length
而类型转换会改变变量的值
let someValue: any this is a string
let strLength: number (stringsomeValue).length // 类型断言
let someValue2 Boolean(someValue) // 类型转换// someValue2 true
类型断言和类型声明对比
注意优先使用类型声明代码更优雅代码质量高
interface SquareConfig {color?: string;width?: number;
}function createSquare(config: SquareConfig): SquareConfig{// ...return config
}// 类型声明
const mySquare: SquareConfig createSquare({ width: 100 });// 类型转换
const mySquare2 createSquare({ width: 100}) as SquareConfig
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/86274.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!