2、接口、枚举、泛型

interface Radio {
  switchRadio(trigger: boolean): void
}

class Car implements Radio { //继承一个接口
  switchRadio(){}
}

class Car1 implements Radio,Batattery { //继承多个接口
  switchRadio(){}
}

 

 

枚举enum

enum Direction {
 Up,
 Down,
 Left = 3,
 Right
}

console.log(Direction.Up) //0
console.log(Direction[0]) //Up
console.log(Direction[3]) //Left

// 赋值完下标后,后面的值会根据前面的下标递增

 

字符串型赋值

enum Direction {
 Up = 'up',
 Down = 'down',
 Left = 'left',
 Right = 'right'
}

const value = 'up'
if(value === Direction.Up){......}

 

常量枚举(提升性能)

const enum Direction {
 Up = 'up',
 Down = 'down',
 Left = 'left',
 Right = 'right'
}

const value = 'up'
if(value === Direction.Up){......}

// 编译完之后
const value = 'up'
if(value === 'up'){......}

 

泛型(generics)

function echo<T>(arg:<T>): T {
  return arg  
}

cosnt result = echo(123) //此时result是number型
const result1 = echo('hahha') //此时result1是string型
......

 

function swap<T,U>(tuple:[T,U]): [U,T] { }

 

约束泛型

interface IWithLength {
  length: number
}

function echoWithLength<T extends IWithLength>(arg: T): T {
  console.log(arg.length)
  return arg
}

const test = echoWithLength('str')  //只要参数支持length方法就不会报错

 

简单约束泛型(约束为数组)

function echoWithArr<T> (arg: T[]): T[] {
  console.log(arg.length)
  return arg
}

const arr = echoWithArr([1,2,3])

 

泛型(约束类简单方法)

class Queue<T> {
  private data = []

  push(item: T) {
    return this.data.push(item)
  }
  
  pop(): T {
    return this.data.shift()
  }
}
const queue = new Queue<number>()
queue.push(1)
console.log(queue.pop().toFixed())

 

泛型(约束类接口方法)

interface KeyPair<T,U> {
  key: T
  value: U
}

let kp1:KeyPair<number, string> = {key:1,value:'string'}
let kp2:KeyPair<string, number> = {key:'str', value:2}

let arr:number[] = [1,2,3]
let arrTwo:Array<number> = [1,2,3]

 

 

类型别名

let sum:(x:number, y:number) => number
const result = sum(1,2)

// 开始定义别名 type aliase
type PlusType = (x:number, y:number) => number
let sum2:PlusType
const result = sum2(1,2)

// 联合类型别名
type StrOrNumber = string | number
let result3: StrOrNumber = '123'
result3 = 123

// 字面量类型(只能是原始类型)
const str:'name' = 'name' // 类型为name值就只能为name
const num:1 = 1

type typeList = 'up' | 'right' | 'down' | left
const Direction:typeList = 'up' //值只能上面四个之一

 

 

 

交叉类型

interface IName {
  name: string
}

type IPerson = IName & {age: number}

let person:IPerson = {name:'123',age:123}

// 类似于接口的extends

 

posted @ 2021-10-18 09:05  JaydenQiu  阅读(41)  评论(0)    收藏  举报