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

     类型保护:就是一些表达式或者关键字在编译时候就能确定在某个作用域内变量的类型
     关键字有:if-else typeof instanceof  prop in obj  a is b is语法

    typeof instanceof

     interface IDoubleFunc {
        (input: string | number | boolean): void
      }
      //typeof关键字来确定变量类型
      const double1: IDoubleFunc = input => {
        if (typeof input === 'string') return input + input
        if (typeof input === 'number') return input * 2
        if (typeof input === 'boolean') return !input
      }
    
      // instanceof 
      class Animal {
        name: string;
        constructor(name: string) {
          this.name = name
        }
      }
      class Bird extends Animal {
        swing: number = 2
      }
      interface IGetNameFunc {
        (animal: Animal): void
      }
      const getName: IGetNameFunc = animal => {
        if (animal instanceof Bird) return animal.swing
        if (animal instanceof Animal) return animal.name //到了这里只能点name了 没有swing提示了
    
      }
      

     prop in obj/obj.hasOwnpropery(prop)

     interface IBird {
        swing: number
      }
      interface IDog {
        leg: number
      }
      interface IGetNumberFunc {
        (x: IBird | IDog): number
      }
      const getNumber: IGetNumberFunc = x => {
        if ('swing' in x) return x.swing
        return x.leg
      }
      getNumber({ swing: 2 })

    x is 类型

    interface IBird {
        name: 'bird',
        leg: number
      }
      interface IDog {
        name1: 'dog'
        leg: number
      }
      type Animal = IBird | IDog
      interface IGetAnimal {
        (animal: Animal): void
      }
      function isBird(x: Animal): x is IBird {
        return x.leg === 2
      }
      const getAnimal: IGetAnimal = animal => {
        if (isBird(animal)) console.log(animal.name);
        else console.log(animal.name1);
      }
      getAnimal({ name: 'bird', leg: 2, })
      
  • 相关阅读:
    转载:SuperMap 网络带宽对B/S项目的影响有多大?如何计算所需要的带宽?
    转载:使用JWT做用户登陆token校验
    转载:互联网在线地图平台对比分析
    jmeter计时器讲解
    ReactNative setNativeProps
    关于xxx.h file not found 的问题
    注册推送通知
    ios ViewController present不同的方向
    ReactNative常见报错
    ios 后台模式
  • 原文地址:https://www.cnblogs.com/xiaoliziaaa/p/14991291.html
Copyright © 2011-2022 走看看