TypeScript 型別學習3
阿新 • • 發佈:2022-04-06
/** * 操作符in 來進行型別縮小 * js中in運算子用來確定物件是否具有某個名稱的屬性 * 所以ts中也有這個,用來縮小潛在的類型範圍 */ //例如“value” in x ,value是字串文字 x代表聯合型別 //true x具有可選或者必需屬性的型別的值 //false 分支的縮小 x需要具有可選或者缺失屬性型別的值 type WJH = { name: string; age: number }; type WH = { name: string; color: string }; function Earth(people: WJH | WH) { if ("age" in people) { console.log(people.name); } if ("color" in people) { console.log(people.name); } } Earth({ age: 18, name: "王佳慧", }); Earth({ color: "blue", name: "呵呵呵呵呵", }); /** * instanceof 操作符縮小 * 測試它左邊的物件是否是它右邊的類的例項,返回 boolean 的資料型別。 * x instanceof A */ function logValue(x: Date | string) { if (x instanceof Date) { console.log(x.toUTCString()); } else { console.log(x.toUpperCase()); } } logValue(new Date()); logValue("wangjiahui"); /** * 型別謂詞 * 想要直接控制整個程式碼的型別變化 * 想要定義一種型別的型別保護 * 我們只需要定一個函式讓他的返回值是型別謂詞就可以 */ type Fish = { swim: () => void; name: string }; type Bird = { fly: () => void; name: string }; function isFish(anmial: Fish | Bird): anmial is Fish { console.log((anmial as Fish).swim !== undefined); return (anmial as Fish).swim !== undefined; } // function checkType<T>(val: any, type: keyof T): val is T { return (val as T)[type] !== undefined; } function getAnmialType(): Fish | Bird { let fish: Fish = { name: "鯊魚", swim: () => { console.log("我是鯊魚呵呵呵"); }, }; let bird: Bird = { name: "麻雀", fly: () => { console.log("我是麻雀嘻嘻嘻"); }, }; return true ? fish : bird; } let pet = getAnmialType(); if (isFish(pet)) { pet.swim(); } else { pet.fly(); } //型別相容 要滿足之前的基礎屬性 TS的反推 //物件的賦值 interface A { name: string; age: number; } let B: A; let C = { name: "wangjiahui", age: 10, color: "blue", }; B = C;