原文:TypeScript基本知识点整理
零、序言
类型断言,可以用来手动指定一个值的类型。
给我的感觉,和 java 中的强制类型转换很像。
常常和联合类型配合使用,如:
// 错误示例
function f13(name : string, age : string | number) {
if (age.length) { //报错
console.log(age.length) //报错
} else {
console.log(age.toString)
}
}
f13('ljy', 21)
//Property 'length' does not exist on type 'string |number'.Property 'length' does not exist on type 'number'
// 使用类型断言示例
function f14(name : string, age : string | number) {
if ((<string>age).length) {//断言
console.log((<string>age).length)//断言
} else {
console.log(age.toString)
}
}
f14('ljy', 21)
注意事项:
类型断言并不是普通意义上的类型转换,断言成一个联合类型中不存在的类型是不允许的:
function toBoolean(something: string | number): boolean {
return <boolean>something;
}
// Type 'string | number' cannot be converted to type 'boolean'