1. 程式人生 > 其它 >Typescript(十一)聯合型別和型別守護

Typescript(十一)聯合型別和型別守護

聯合型別:通俗點說就是一個變數可能有多種型別。

比如:一個人(person)有可能是老師(teacher),也有可能是服務員(waiter),但是不可能同時是老師和服務員。

interface teacher{
    type:string;
    say:()=>{};
}
 
interface waiter{
    type:string;
    run:()=>{};
}
// 呼叫
function person(animal: waiter | teacher) {}

animal就是一個聯合型別,但是現在直接呼叫animal中的方法的時候會報錯:

function
person2(animal: Waiter | Teacher) { animal.say(); }

因為,其二種介面中的方法即屬性可能是不同的。

這個時候,我們就需要傳說中的型別保護

一:型別保護-型別斷言

型別斷言就是通過斷言的方式確定傳遞過來的準確值,比如上面的程式,如果type是teacher,說明他就是老師,這時候就可以通過斷言animal as Teacher,然後直接呼叫say方法,程式就不再報錯了。

同樣如果type是waiter,說明就是服務員,這時候呼叫run()方法,就不會報錯了。

這就是通過斷言的方式進行型別保護。也是最常見的一種型別保護形式。

interface
teacher{ type:string; say:()=>{}; } interface waiter{ type:string; run:()=>{}; } /** * 型別斷言 * @param animal */ function person1(animal: waiter | teacher) { // 通過介面中的型別判斷 if (animal.type == 'teacher') { (animal as teacher).say(); } else { (
animal as waiter).run(); } }

二:型別保護-in 語法

使用in來判斷介面中是否有當前你要呼叫的語法。程式碼如下:

/**
 * in 語法
 * @param animal 
 */
function person2(animal: waiter | teacher) 
{
    // 通過介面中的型別判斷
    if ("say" in animal) 
    {
        animal.say();
    }
    else
    {
        animal.run();
    }
}

三:型別保護-typeof語法

先來寫一個新的add方法,方法接收兩個引數,這兩個引數可以是數字number也可以是字串string,如果我們不做任何的型別保護,只是相加,這時候就會報錯。程式碼如下:

/**
 * typeof 語法
 */
function add(first: string | number,secord:string | number) 
{
    return first + secord; // 這條語句會報錯
}

正確的寫法如下:

/**
 * typeof 語法
 */
function add(first: string | number,secord:string | number) 
{
    if(typeof first === 'string' || typeof secord === 'string')
    {
         return `${first}${secord}`;
    }
    return first + secord; 
}

四:型別保護-instanceof 語法

比如現在要作型別保護的是一個物件,這時候就可以使用instanceof語法來作。現在先寫一個NumberObj的類,程式碼如下:

class NumberObj {
  count: number;
}

然後我們再寫一個addObj的方法,這時候傳遞過來的引數,可以是任意的object,也可以是NumberObj的例項,然後我們返回相加值,當然不進行型別保護,這段程式碼一定是錯誤的。

function addObj(first: object | NumberObj, second: object | NumberObj) {
  return first.count + second.count;
}

報錯不要緊,直接使用instanceof語法進行判斷一下,就可以解決問題。

function addObj(first: object | NumberObj, second: object | NumberObj) {
  if (first instanceof NumberObj && second instanceof NumberObj) {
    return first.count + second.count;
  }
  return 0;
}

另外要說的是,instanceof 只能用在類上。這節課我大概說了四種類型保護的方式,每種方式都在不同場景中使用(還有一些不太常用的型別保護方式),可能需要自己深刻理解。

有好的建議,請在下方輸入你的評論。

歡迎訪問個人部落格
https://guanchao.site

歡迎訪問小程式:

在這裡插入圖片描述