zoukankan      html  css  js  c++  java
  • typescript(四) 类型保护

    类型保护指的是确认分支作用域中的类型。可以更具体的调用参数上的属性和方法。

    1. 基本类型保护

    function first(a: number|string|boolean):number {
      if(typeof a === 'number') {
        return a;
      } else if(typeof a === 'string') {
        return a.length;
      } else {
        return 0;
      }
    }

    2. 类保护-instanceof

    class Animal{
      name: string = '';
    }
    class Bird extends Animal {
      sing: string = 'song';
    }
    class Dog extends Animal {
      eat: string = 'bone';
    }
    function second(animal: Animal) {
      if (animal instanceof Bird) {
        return animal.name;
      } else if(animal instanceof Dog) {
        return animal.eat;
      } else {
        return animal.name;
      }
    }

    3. null保护

    开启了strictNullChecks, 则不能直接调用变量可能为null的变量上的方法和属性。

    1.  使用!

    function t(str: string|null) {
      return str!.length
    }

    2. 使用 ||

    function t1(str: string|null) {
      str = str || '';
      return str.length
    }

    3. 使用链判断运算符-?.

    ⚠️该运算符处于stage1阶段,现不能直接使用;需要安装插件

    let a = {b:0};
    let c = a?.b; 
    // 原理: 如果变量为null,或者该变量不存在某属性
    if (!a) {
      return undefined
    } else {
      return a.b
    }

    4. 联合类型保护

    1. 可以通过同名属性的不同值进行区分

    interface WarningButton {
      text: 'warning',
      color: 'yellow'
    }
    interface DangerButton {
      text: 'danger',
      do: 'be careful'
    }
    type Button = WarningButton | DangerButton;
    function chooseBtn(button: Button) {
      if(button.text === 'warning') {
        return button.color;
      } else if(button.text === 'danger') {
        return button.do;
      }
    }

    2. 可以通过各自的特有属性进行区分-in

    interface WarningBtn {
      text: string,
      color: string
    }
    interface DangerBtn {
      text: string,
      do: string
    }
    type Btn = WarningBtn | DangerBtn;
    function ChooseBtn(btn: Btn) {
      if ('color' in btn) {
        return btn.color;
      } else if('do' in btn) {
        return btn.do;
      }
    }

    3. 自定义实现类型保护-is

    当方法1,2都不能满足条件的时候

     interface Bird {
       legs: number
     }
     interface Dog {
       legs: number
     }
     type Animals = Bird | Dog;
     function isBird(x: Animals):x is Bird {
       return x.legs === 2;
     } 
     function diffAni(x: Animals) {
       if(isBird(x)) {
         // to be Bird
       } else {
         // to be  Dog
       }
     }
  • 相关阅读:
    获取请求浏览器信息
    (转)获取页面 鼠标位置
    (转)location.href 用法
    (转)异常的处理
    (转载)提高ASP.NET Web应用性能的技巧
    赶集网二手数据.py
    豆瓣top250.py
    爬取58二手数据.py
    使用类和实例.py
    爬取小猪短租房.py文件
  • 原文地址:https://www.cnblogs.com/lyraLee/p/12396524.html
Copyright © 2011-2022 走看看