TypeScript-进阶(三)-类型保护函数

73 阅读1分钟

1.定义

类型保护函数是一种用于在运行时检查并区分变量类型的函数。
通过调用该函数,会触发TS的类型保护,该函数必须返回boolean

2.使用

定义一个父类,两个子类,其中一个子类有isJump和isFire方法,分别实例化这两个子类后放入一个数组,遍历这个数组后判断有这两个方法的要自动调用

interface IFireJump {
    isFire: () => void,
    isJump: () => void
}


class TankA { }

class TankB extends TankA implements IFireJump {
    isFire() {
        console.log('火');

    }
    isJump() {
        console.log('跳');
    }
}

class TankC extends TankA { }


const arr: TankA[] = [
    new TankB(),
    new TankC()
]

// 类型保护函数
function hasType(type: object): type is IFireJump {
    if ((type as IFireJump).isFire && (type as IFireJump).isJump) {
        return true
    }
    return false
}

arr.forEach(item => {
    if (hasType(item)) {
        item.isFire();
        item.isJump()
    }
})