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, })
      
  • 相关阅读:
    WebApi接口访问频率控制的实现
    一分钟告诉你究竟DevOps是什么鬼?
    大多数企业不知道的隐形成本
    29个网络营销必须知道的数据
    如何让自己的生活有品质感?
    一则有意思的产品小故事
    免费学习编程的9个地方
    营销,就是营销人性的弱点!
    网络营销行业十大看了就想吐的“滥词”
    高质量的内容是SEO的关键
  • 原文地址:https://www.cnblogs.com/xiaoliziaaa/p/14991291.html
Copyright © 2011-2022 走看看