Typescript 进阶

49 阅读2分钟

Typescript 进阶


常用写法

interface 与 type 声明类型

 interface Person {
   age: string
 }

 // interface 具有扩增能力
 interface Person {
  name: string
 }

 const p:Person = {
  age:1,
  name:'张三'
 }
 // 错误案例
 type Person = {
  age: number
 }

 // 报错, type 不支持扩增能力
 type Person = {
  name: string
 }
  // 正确写法
  type PersonAttrs1 = {
    age: number
  }
  type PersonAttrs2 = {
    name: string
  }
  type Person = PersonAttrs1 & PersonAttrs2
  const p: Person = {
    age:1,
    name:'张三'
  }

type声明类型,更强调一致性interface声明类型,更灵活,支持扩增属性类型

操作符 “&”、“|”

type LeftHand = {
  left: boolean
}
type RightHand = {
  right: boolean
}

// 这个人既有左手也有右手
type Person = LeftHand & RightHand
const p: Person = {
  left: true,
  right: true
}

// 这个人要不只有左手 要不只有右手
type Person1 = LeftHand | RightHand
const p1: Person1 = {
  left: true
}
const p2: Person1 = {
  right: true
}

// 报错,不符合
const p3: Person1 = {
  left: true,
  right: true
}

类型声明与类型签名


// 只要用 type interface 这种声明关键字,都称为类型声明
type Person = {}
interface Animal {}

// 称为类型签名
const p: Person = {}
const a: Animal = {}

需要大家正确理解描述词语,这样有助于更好理解泛型及推导类型

泛型

// 简单常见泛型
const strArr: Array<string> = []
// 等于 const strArr: string[] = []


// 常用泛型
type TableItem<T = string> = {
  id: string
  prop: T
}

// 更高阶的用法
type TableItem<T extends Record<string, any> = any> = {
  id: string
  prop: keyof T
  render?: (row:T) => any
}

泛型用好,可以使其他人在维护或者使用时,更容易去收窄类型、提高效率。

约束类型

 // 常见约束
 type TableItem<T extends string = string> = {
  id: string
  prop: T
}

 // 报错,因为已经约束泛型类型,必须为 string
 const tableList: TableItem<number>[] = []

 // 正确
 const tableList: TableItem<'id'|'name'> = []

自推导

// 接口1
type listRsp1 = {
  list?: number[]
} 

// 接口2
type listRsp2 = {
  list?: string[]
}

// 接口3
type listRsp3 = {
  list?: object[]
}


// 推导类型出 list 的类型
type ExtractItemFromListPage<T = any> = T extends {
  list?: (infer R)[]
}
  ? R
  : any

// 接口1的 item
type itemRsp1 = ExtractItemFromListPage<listRsp1>
// 接口2的 item
type itemRsp2 = ExtractItemFromListPage<listRsp2>
// 接口3的 item
type itemRsp3 = ExtractItemFromListPage<listRsp3>