typescript中的類型保護(hù)

類型保護(hù): 當(dāng)使用聯(lián)合類型時(shí), 我們必須盡量把當(dāng)前值的類型收窄為當(dāng)前值的實(shí)際類型,類型保護(hù)就是可執(zhí)行運(yùn)行時(shí)檢查的一種表達(dá)式,用于確保此類型在一定范圍內(nèi)。

實(shí)現(xiàn)類型保護(hù)的四種方式:

  1. in 關(guān)鍵字
interface Dog {
  name: string;
  bark: () => void;
}
interface Bird {
  name: string;
  fly: () => void;
}
type Animal = Dog | Bird;
let animal: Animal = {
  name: 'little bird',
  fly: () => {
    console.log('fly')
  }
} 
if('fly' in animal) {
  animal.fly();
}
  1. typeof 關(guān)鍵字
let height: string | number;

function setHeight(height: string | number) {
  if(typeof height === 'number') {
    return `${height}px`;
  }
  if(typeof height === 'string') {
    return height;
  }
}
  1. instanceof 關(guān)鍵字
interface Person {
  major: () =>void;
}
class Teacher implements Person {
  constructor(private studying: string) {}
  major() {
    console.log(`student study ${this.studying}`)
  }
}
class Student implements Person {
  constructor(private teaches: string) {}
  major() {
    console.log(`teacher teaches ${this.teaches}`)
  }
}
let person: Person = new Teacher('math');
if(person instanceof Teacher) {
  // 收窄類型為 Teacher
  console.log(true)
}
  1. 自定義類型保護(hù)的類型謂詞 (type predicate)
function isNumber(x: any): x is number {
    return typeof x === 'number'
}
interface User {
    type: 'user';
    name: string;
    age: number;
    occupation: string;
}

interface Admin {
    type: 'admin';
    name: string;
    age: number;
    role: string;
}

export type Person = User | Admin;

export const persons: Person[] = [
    { type: 'user', name: 'Max Mustermann', age: 25, occupation: 'Chimney sweep' },
    { type: 'admin', name: 'Jane Doe', age: 32, role: 'Administrator' },
    { type: 'user', name: 'Kate Müller', age: 23, occupation: 'Astronaut' },
    { type: 'admin', name: 'Bruce Willis', age: 64, role: 'World saver' }
];

export function isAdmin(person: Person): person is Admin {
    return person.type === 'admin';
}

export function isUser(person: Person): person is User {
    return person.type === 'user';
}

export function logPerson(person: Person) {
    let additionalInformation: string = '';
    if (isAdmin(person)) {
        additionalInformation = person.role;
    }
    if (isUser(person)) {
        additionalInformation = person.occupation;
    }
    console.log(` - ${person.name}, ${person.age}, ${additionalInformation}`);
}

console.log('Admins:');
persons.filter(isAdmin).forEach(logPerson);

console.log();

console.log('Users:');
persons.filter(isUser).forEach(logPerson);
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容