本节介绍 ts 中的联合类型和类型保护的几种方法
1 2 3 4 5 6 7 8 9 10 11 12 13
| interface CustomModel { goods: boolean; name: string; age: number; buy: () => {}; }
interface MerchantModel { goods: boolean; name: string; age: number; sell: () => {}; }
|
as 断言
1 2 3 4 5 6 7
| function judgePeopleAs(people: CustomModel | MerchantModel) { if (people.goods) { (people as MerchantModel).sell(); } else { (people as CustomModel).buy(); } }
|
in 断言
1 2 3 4 5 6 7
| function judgePeopleIn(people: CustomModel | MerchantModel) { if ("buy" in people) { people.buy(); } else { people.sell(); } }
|
typeof 类型检查
1 2 3 4 5 6
| function addStrOrNum(first: string | number, second: string | number) { if (typeof first === "string" || typeof second === "string") { return `${first} ${second}`; } return first + second; }
|
instanceof (只能用在类中)
1 2 3 4 5 6 7 8 9 10
| class NumberObj { count: number = 0; }
function AddObj(first: object | NumberObj, second: object | NumberObj) { if (first instanceof NumberObj && second instanceof NumberObj) { return first.count + second.count; } return 0; }
|