typescript 的几种基本的类型保护
2020-09-16 本文已影响0人
两朵小黑云
interface Brid {
fly: boolean
sing: () => {}
}
interface Dog {
fly: boolean
bark: () => {}
}
// 联合类型仅提示共有属性
function tranAnial(animal: Brid | Dog) {
// 类型断言 实现类型保护
if (animal.fly) {
(animal as Brid).sing()
} else {
(animal as Dog).bark()
}
}
function tranAnialSecond(animal: Brid | Dog) {
// in 语法实现类型保护
if ('sing' in animal) {
animal.sing()
} else {
animal.bark()
}
}
function add(first: string | number, second: string | number) {
// typeof 语法实现类型保护
if (typeof first === 'string' || typeof second === 'string') {
return `${first}${second}`
}
return first + second
}
// 使用 instanceof 语法做类型保护
class NumberObj {
// 声明变量
count: number
// 创建构造函数
constructor(count: number) {
this.count = count
}
}
function addSecond(first: object | NumberObj, second: object | NumberObj) {
if (first instanceof NumberObj && second instanceof NumberObj) {
return first.count + second.count
}
return 0
}