ts 类型体操 easy篇

·  阅读 38

总结

1、Pick

type MyPick<T, K extends keyof T> = {
    [k in K]: T[k]
}
复制代码

2、Readonly

type MyReadonly<T> = {
    readonly [k in keyof T]: T[k]
}
复制代码

3、tuple to object

type TupleToObject<T extends readonly (string | number)[]> = {
    [k in T[number]]: k
}
复制代码

注意: any要改成(string | number)

4、First

type First<T extends any[]> = T['length'] extends 0 ? never : T[0]
复制代码

注意: ts中不能说 ===, 要用extends来代表,比如这里不能直接T['length'],或者写T['length'] === 0

5、tuple length

type Length<T extends readonly any[]> = T['length']
复制代码

6、Exclude

type MyExclude<T, U> = T extends U ? never : T
复制代码

7、Awaited

type MyAwaited<T extends Promise<any>> = 
T extends Promise<infer U> ?
    U extends Promise<infer K> ?
        MyAwaited<Promise<K>>
        : U
  : never
复制代码

8、If

type If<C extends boolean, T, F> = C extends true ? T : F
复制代码

9、Concat

type Concat<T extends any[], U extends any[]> = [...T, ...U]
复制代码

10、Includes (难度+)

type Equal<X, Y> = (<Res>() => Res extends X ? true : false) extends (<Res>() => Res extends Y ? true : false) ? true : false

type Includes<T extends readonly any[], U> =
T extends [infer First, ...infer Rest]
  ?
  Equal<First, U> extends true
    ? true
    : Includes<Rest, U>
  :
  false
复制代码

11、Push

type Push<T extends any[], U> = [...T, U]
复制代码

12、Unshift

type Unshift<T extends any[], U> = [U, ...T]
复制代码

13、MyParameters

type MyParameters<T> = T extends (...args: infer a) => void ? a : []
复制代码
分类:
前端
收藏成功!
已添加到「」, 点击更改