TS-8 泛型

2023-03-14  本文已影响0人  RickyWu585
type Person = {
  name: string
}

// 这里extends可以用类型兼容来理解
type LikePerson<T> = T extends Person ? 'yes' : 'no'

type A = LikePerson<{name: string,age: number}>  // yes
type B = LikePerson<string> // no
type ToArray<T> = T extends unknown ? T[] : 'xxx'

type A = ToArray<string | number>  // string[] | number[]
type B = ToArray<never>  //never
type Person = {
  name: string
  age: number
}

type GetKeys<T> = keyof T
type PersonKeys = GetKeys<Person>  // 'name' | 'string'
type Person = {
  name: string
  age: number
}

// 泛型约束
type GetKeyType<T,K extends keyof T> = T[K] 

type Result = GetKeyType<Person,'age'> // number
type GetKeyType<T,K extends keyof T> = T[K] 
type Person = {
  name: string
  age: number
}

type ReadOnlyType<T> = {
 readonly [K in keyof T]:  T[K]
}

type A = ReadOnlyType<Person> // {readonly name: string; readonly age:number}
type Person = {
  name: string
  age: number
}
// 所有属性必填
type Required<T> = {
  [K in keyof T] -? : T[K]
}

// K 是泛型,不能用 [k : K],只能用 in
type Record<K extends string | number | symbol,T> = {
  [k in  K] : T
}

// 对 T 做分配律,分配律只对前面的有效
type Exclude<T,K > = T extends K ? never : T
type X = Exclude<1 | 2 | 3,1 | 2> // 3
// ---相反---
type Extract<T,K> = K extends T ? K : never
type Y = Extract<1 | 2 | 3,2 | 4> // 2

type Pick<T,K extends keyof T> = {
  [k in K]: T[k]
} 

type Omit<T,Key extends keyof T> = Pick<T,Exclude<keyof T,Key>>
// ---or---
type Omit<T,Key extends keyof T> = {
  [k in keyof T as (k extends Key ? never : k)] : T[k]
} 
type Z = Omit<Person,'age'> // {name: string}

// -readonly
type Mutable<T> = {
  -readonly [k in keyof T]: T[k]
}
上一篇下一篇

猜你喜欢

热点阅读