/** * 操作符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;