zoukankan      html  css  js  c++  java
  • 类型保护

    自定义类型保护,文档中说:一旦检查过类型,就能在之后的每个分支里清楚地知道 pet的类型的话就好了,但并未说哪种分支有效

    亲测:if else 、while有效,switch无效

    interface Bird {
        fly();
        layEggs();
    }
    
    interface Fish {
        swim();
        layEggs();
    }
    
    function getSmallPet(): Fish | Bird {
        let p:Bird
        return p
    }
    
    let pet = getSmallPet();
    
    //根据返回值来判断谓语是否正确,之后在分支中就无需对谓语的主进行判断(主谓宾)
    function isFish(pet: Fish | Bird): pet is Fish {
        return (<Fish>pet).swim !== undefined;
    }
    
    let p1= getSmallPet()
    
    if(isFish(p1)){
        p1.swim()
    }else {
        p1.fly()
    }
    
    switch(isFish(p1)){
        case true: p1.swim(); //亲测报错
        case false: p1.fly();
    }
    
    while(isFish(p1)){
        p1.swim()
    }

    --------------------------------------


    包括typeof类型保护(适用于简单的基本类型)

    if else 、while也是有效的

    function getVal(): number | string {
        return 1
    }
    
    let v = getVal();
    
    if(typeof v== 'number'){
        v++
    }else {
        v.split(',')
    }
    
    while(typeof v== 'number'){
        v++
    }

    备注:

    即便是在ts里typeof依旧是es的规范

  • 相关阅读:
    ubuntu安装pgAdmin 4
    python 读取文件
    byobu copy
    vim快捷键汇总
    python 停止线程
    python执行外部命令并获取输出
    gevent mysql
    python类型转换
    量化交易
    Java集合:HashMap底层实现和原理(源码解析)
  • 原文地址:https://www.cnblogs.com/yanze/p/12250116.html
Copyright © 2011-2022 走看看