美文网首页
typescript 的几种基本的类型保护

typescript 的几种基本的类型保护

作者: 两朵小黑云 | 来源:发表于2020-09-16 23:05 被阅读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
    }
    
    

    相关文章

      网友评论

          本文标题:typescript 的几种基本的类型保护

          本文链接:https://www.haomeiwen.com/subject/torkyktx.html