ts类型保护

249 阅读1分钟

四种方式 : 类型断言(as)、in语法、typeof、instanceof

interface Bird {
  fly: boolean;
  sing: () => {};
}
interface Dog {
  fly: boolean;
  bark: () => {};
}

//类型断言的方式 function train(animal: Bird | Dog) { if (animal.fly) { (animal as Bird).sing(); } else { (animal as Dog).bark(); } }

//in语法来做类型保护 function trainSecond(animal: Bird | Dog) { if ("sing" in animal) { animal.sing(); } else { animal.bark(); } }

function add(first: number | string, second: string | number) { if (typeof first === "string" || typeof second === "string") return ${first} + ${second}; return first + second; } //报错:属性“count”没有初始化表达式,且未在构造函数中明确赋值。ts(2564) //需要tsconfig.json中 "strict": false class NumberObj { count: number; } function addSecond(first: object | NumberObj, second: object | NumberObj) { if (first instanceof NumberObj && second instanceof NumberObj) return first.count + second.count; return 0; }