Typescript使用指南

68 阅读1分钟

元组

let user: [string, number] = ['Leslie', 18]

接口

interface User {
  readonly id: string;
  name: string;
  age: number;
}

const user: User = {
  id: '001',
  name: 'Leslie',
  age: 18
}

函数

interface Count {
    (a: number, b: number): number
}

type Count = (a: number, b: number) => number

const count: Count = (a, b) => a + b

类型推论

let name = 'leslie'

联合类型

let numOrStr: number | string

类型断言

function getLength(input: string | number): number {
  const str = input as string

  if(str.length) {
    return str.length
  }

  const num = input as number
  return num.toString().length
}

枚举

enum Direction {
  horizontal: 'HORIZONTAL',
  vertical: 'VERTICAL'
}

泛型(Generics)

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

const result1 = echo('leslie')

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

const result2 = swap(['leslie', 18])

约束泛型

interface WithLength {
  length: number;
}

function echoWithLength<T extends WithLength>(arg: T): T {
  return arg
}

泛型在类和接口中使用

// 类
class Queue<T> {
  private data = []

  push(value: T) {
    return this.data.push(value)
  }

  pop(): T {
    return this.data.pop()
  }
}

const queue = new Queue<number>()

// 接口
interface KeyPair<T, U> {
  key: T;
  value: U;
}

类型别名、字面量和交叉类型

// 类型别名
type PlusType = (x: number, y: number) = number

// 字面量
type Direction = 'horizontal' | 'vertical'

// 交叉类型
interface Name {
  name: string;
}

type User = Name & { age: number }