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
       }
     }
  • 相关阅读:
    django虚拟环境中报E: 无法定位软件包 sqliteman
    创建django项目
    Django虚拟环境安装
    python学习笔记(三)
    python学习笔记(二)
    python学习笔记(一)
    python 类属性和实例属性
    决策树的基本ID3算法
    KNN算法的简单实现
    webClient
  • 原文地址:https://www.cnblogs.com/lyraLee/p/12396524.html
Copyright © 2011-2022 走看看