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, })
  

 

 

posted on 2021-07-09 16:49  章画  阅读(232)  评论(0编辑  收藏  举报

导航