原文: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'
