TS试炼-1

摘要:

本项目意在于让你更好的了解 TS 的类型系统,编写你自己的类型工具,或者只是单纯的享受挑战的乐趣!我们同时希望可以建立一个社区,在这里你可以提出你在实际环境中遇到的问题,或者帮助他人解答疑惑 - 这些问题也可能被选中成为题库的一部分!

1、Pick 挑选指定属性

ts 复制代码
// https://github.com/type-challenges/type-challenges/blob/main/questions/00004-easy-pick/README.zh-CN.md
type MyPick<T, K extends keyof T> = {
  [P in K]: T[P]
}

2、Readonly 全部一级属性只读

ts 复制代码
// https://github.com/type-challenges/type-challenges/blob/main/questions/00007-easy-readonly/README.zh-CN.md
type MyReadonly<T> = {
  readonly [P in keyof T]: T[P]
}

3、元组转换为对象

ts 复制代码
// https://github.com/type-challenges/type-challenges/blob/main/questions/00011-easy-tuple-to-object/README.zh-CN.md
type TupleToObject<T extends readonly PropertyKey[]> = {
  [P in T[number]]: P
}

4、数组第一个元素

ts 复制代码
// https://github.com/type-challenges/type-challenges/blob/main/questions/00014-easy-first/README.zh-CN.md
type First<T extends any[]> = T['length'] extends 0 ? never : T[0]
type First<T extends any[]> = T extends { length: 0 } ? never : T[0]
type First<T extends any[]> = T extends [] ? never : T[0]
type First<T extends any[]> = T[number] extends never ? never : T[0]
type First<T extends any[]> = T extends [infer F, ...infer R] ? F : never

5、获取元组长度

ts 复制代码
// https://github.com/type-challenges/type-challenges/blob/main/questions/00018-easy-tuple-length/README.zh-CN.md
type Length<T extends readonly unknown[]> = T['length']

6、Exclude 排除元组项

ts 复制代码
// https://github.com/type-challenges/type-challenges/blob/main/questions/00043-easy-exclude/README.zh-CN.md
type MyExclude<T, U> = T extends U ? never : T

7、Awaited 获取Promise返回值

ts 复制代码
// https://github.com/type-challenges/type-challenges/blob/main/questions/00189-easy-awaited/README.zh-CN.md
type MyAwaited<T> = T extends {then: (onfulfilled: (args: infer V) => unknown) => unknown} ? MyAwaited<V> : T
type MyAwaited<T> = T extends PromiseLike<infer V> ? MyAwaited<V> : T

8、If 判断语句

ts 复制代码
// https://github.com/type-challenges/type-challenges/blob/main/questions/00268-easy-if/README.zh-CN.md
type If<C extends boolean, T, F> = C extends true ? T : F

9、Concat 拼接数组类型

ts 复制代码
// https://github.com/type-challenges/type-challenges/blob/main/questions/00533-easy-concat/README.zh-CN.md
type Concat<T extends readonly unknown[], U extends readonly unknown[]> = [...T, ...U]

10、Includes 判断指定类型是否在数组类型中出现

ts 复制代码
// https://github.com/type-challenges/type-challenges/blob/main/questions/00898-easy-includes/README.zh-CN.md
type MyEqual<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false
type Includes<T extends readonly any[], U> = T extends [infer F, ...infer R] ? Equal<F, U> extends true ? true : Includes<R, U> : false

评论

0条评论

logo

暂无内容,去看看其他的吧~