typescript中的类型保护

首先看个例子

enum Type{Strong,Week}
class Black{
    hellowBlack(){console.log(this.rgb))}
    rgb:string = '0,0,0';
}
class White{
   hellowWhite(){console.log(this.hex16)}
   hex16:string = 'ffffff';
}
function getColor(type:Type){
    const color = Type.Strong === type ? new Black() : new White();
    //下面color.hellowBlack|hellowWhite由于没有约束,所以找不到hellowBlack,这时要使用断言color as Black | White
    if((color as Black).hellowBlack){
        (color as Black).hellowBlack();
    }else{
        (color as White).hellowWhite();
    }
    return color
}

上面的代码中,很显然不是一个理想的方案,代码的可读性很差,此时我们就需要用到typescript的类型保护机制;

那么什么是typescript的类型保护机制呢?

答:能在特定的区块中保证变量属于某种确定的类型
可以在此区块中放心的引用此类型的属性,或者调用此类型的方法

1.instanceof关键字

...
function getColor(type:Type){
    const color = Type.Strong === type ? new Black() : new White();
    if(color instanceof Black){
        color.hellowBlack();
    }else{
        color.hellowWhite(); 
    }
    return color
}

2.in 关键字

...
function getColor(type:Type){
    const color = Type.Strong === type ? new Black() : new White();
    if('rgb' in color){ // 'hellowBlack' in color
        color.hellowBlack()
    }else{
        color.hellowWhite
    }
    return color
}

3.typeof 关键字

function (x:string|[]){
    let arr= [];
    if(typeof x === 'string'){ // 'hellowBlack' in colo
        arr = x.split(',');
    }else{
        arr = x.splice(0,1)
    }
    return x;
}

 4.is:创建类型保护函数

我们来改造1中的例子:首先添加一个isBlack函数,然后通过isBlack来判断当前参数

enum Type{...}
class Black{...}
class White{...}

//使用 is 来确认参数 color 是一个 Black 类型
function isBlack(color:Black|White):color is Black{
    return (color as Black).hellowBlack !== undefined;
};
function getColor(type:Type,x:string|[]){
    const color = Type.Strong === type ? new Black() : new White();
    if(isBlack(color)){
        color.hellowBlack()
    }else{
        color.hellowWhite()
    }
    return color;
}

猜你喜欢

转载自blog.csdn.net/l284969634/article/details/105363887