TypeScript(下)语法/应用

45 阅读2分钟

类型守卫

JavaScript动态语言,其中的参数,值可以是多种类型的(多态) => 需要区别对待每种状态,确保对参数/值操作合法

区分联合类型

  1. switch

    const convert = (c: 'a' | 1){
       switch(c){
         case 1:
           return c.toFixed();
         case 'a':
           return c.toUpperCase();
       }
    }
    
  2. 字面量恒等

    if(c === 1){...}
    
  3. typeof 不可枚举时

  4. instanceof 参数时类

  5. in

  6. keyof 操作符可以获得某种类型的所有键,返回联合类型

   interface Person{
     name:string,
     age:number
   }
   keyof Person  name|age

区分枚举类型

枚举类型,最好不和 除了自身以外的任何枚举/类型比较

  enum A{
      one,
      two
  }
  const cpwithself = (param: A) =>{
     if(param === 1) //不好,因为枚举类型不稳定,也可能不是从0开始
     if(param === A.two){////////////////////////
        ...
      }
  }

类型兼容

判断一个类型是否可以赋值给其他类型

  1. 子类型
  2. 结构类型
  • 两个类型结构一致,是可以互相兼容的
  • 如果类型a不仅拥有类型b的全部属性和方法,还有其他属性方法,a可以兼容b
  1. 是否可以extends继承其他接口类型/类

在TypeScript中安全的使用JavaScript库

  1. declare关键字 声明全局的变量,方法,类,对象

    // 不需要声明具体实现,因为已经在其它库中实现了,只需要声明类型
    declare let val1: string;
    declare function toStr(x: number): string;
    
  2. declare namespace

单例模式在ts中的应用

限制类只能生成一个实例对象

class Axios{
   private static instance: Axios | null = null; // 属性帮助判断只能生成一个实例
   private constructor(){
     // 构造函数private,外部无法调用生成对象
   }
   static make(): Axios{
      if(Axios.instance == null){
          // 创建axios实例
          Axios.instance = new Axios();
      }
      return Axios.instance
   }
}
const instance = Axios.make();

abstract抽象类在ts中的使用

  • 抽象类 - 定义一个规范(需要包含抽象属性/抽象方法)具体需要在子类/派生类中实现
  • 抽象类不能直接new 即不能直接实例化
  • abstract定义抽象类和方法,
abstract class Animation{
   abstract name: string; //抽象属性
   abstract move(): void; //抽象方法
   public getPop(){ ... }
}
class Tank extends Animation{
   name: string = 'aaaa'
   public move(): void{
      console.log('adsfdsf')
   }
}