Typescript - 類型斷言


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM