ts type類型 高級類型 類型保護

type

type 關鍵字用來定義一種類型
舉個例子

type Methods = 'GET' | 'POST' | 'PUT' | 'DELETE'
let method: Methods
method = 'PUT' // OK
method = 'aaa' // error
交叉類型

表示將多個類型合并為一個類型,多用在混入

function mixin <T, U>(first: T, later: U): T & U {
    // let res = <T & U>{}
    let res = {} as T & U
    for (let id in first) {
        (<any>res)[id] = (<any>first)[id];
    }
    for (let id in later) {
        if (!(res as any).hasOwnProperty(id)) {
            (<any>res)[id] = (<any>later)[id];
        }
    }
    return res
}

聯合類型

表示變量可能的類型

let a : number | string
a = 1
a = 'test'

標識為聯合類型的變量,只能調用聯合類型共有的屬性或者方法

class Bird {
    fly () {
        console.log('fly')
    }

    eat () {
        console.log('bird eat..')
    }
}
class Fish {
    swim () {
        console.log('swim')
    }

    eat () {
        console.log('fish eat..')
    }
}

function getAnimal (): Bird|Fish {}

getAnimal().eat()
getAnimal().swim  // error
類型保護

繼續上面的例子
假設我們確實要訪問非共有屬性或者方法,可以使用類型斷言

// 使用類型斷言
(getAnimal() as Fish).swim();
(getAnimal() as Bird).fly();

這樣的話我們不得不多次使用類型斷言,假若我們一旦檢查過類型,就能在之后的每個分支里清楚地知道類型的話就好了。

類型保護就可以做到,類型保護就是一些表達式,它們會在運行時檢查以確保在某個作用域里的類型。 要定義一個類型保護,我們只要簡單地定義一個函數,它的返回值是一個 類型謂詞

function isFish(pet: Fish | Bird): pet is Fish {
    return (<Fish>pet).swim !== undefined;
}

pet is Fish 就是類型謂詞。 謂詞為 parameterName is Type 這種形式,parameterName 必須是來自于當前函數簽名里的一個參數名

通過類型保護,typeScript 可以推斷 if 分支的 pet 一定是 Fishelse 分支的一定是 Bird

let pet = getAnimal()
if (isFish(pet)) {
    pet.swim()
} else {
    pet.fly()
}

此外也可以使用 typeofinstanceof 做類型保護

function checkType (val: number | string) {
    if (typeof val === 'number') {}
    if (typeof val === 'string') {}
}

function checkInstance (val: Bird | Fish) {
    if (val instanceof Bird) {}
    if (val instanceof Fish) {}
}

注意, typeof 只有和基本類型(number,string,boolean,symbol)通過 ===, !== 比較時,才會被識別為類型保護

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容