TS试炼-2

摘要:

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

1、Push 后添加

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

2、Unshift 前添加

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

3、Parameters 函数参数类型

ts 复制代码
// https://github.com/type-challenges/type-challenges/blob/main/questions/03312-easy-parameters/README.zh-CN.md
type MyParameters<T extends (...args: unknown[]) => unknown> = T extends (...args: infer P) => unknown ? P : never

4、ReturnType 函数返回类型

ts 复制代码
// https://github.com/type-challenges/type-challenges/blob/main/questions/00002-medium-return-type/README.zh-CN.md
type MyReturnType<T extends Function> = T extends (...args: any) => infer V ? V : never

5、Omit 剔除属性

ts 复制代码
// https://github.com/type-challenges/type-challenges/blob/main/questions/00003-medium-omit/README.zh-CN.md
type MyOmit<T, K extends keyof T> = {
  [P in keyof T as P extends K ? never : P]: T[P]
}

6、对象部分属性只读

ts 复制代码
// https://github.com/type-challenges/type-challenges/blob/main/questions/00008-medium-readonly-2/README.zh-CN.md
type MyReadonly2<T, K extends keyof T = keyof T> = {
  readonly [P in K]: T[P]
} & {
  [P in keyof T as P extends K ? never : P]: T[P]
}
type MyReadonly2<T, K extends keyof T = keyof T> = Omit<T, K> & Readonly<Pick<T, K>>;

7、对象属性只读(递归)

ts 复制代码
// https://github.com/type-challenges/type-challenges/blob/main/questions/00009-medium-deep-readonly/README.zh-CN.md
type DeepReadonly<T> = {
  readonly [P in keyof T]: keyof T[P] extends never ? T[P] : DeepReadonly<T[P]>
}

8、元组转合集

ts 复制代码
// https://github.com/type-challenges/type-challenges/blob/main/questions/00010-medium-tuple-to-union/README.zh-CN.md
type TupleToUnion<T extends unknown[]> = T[number]
type TupleToUnion<T extends unknown[]> = T extends Array<infer V> ? V : never

9、可串联构造器

ts 复制代码
// https://github.com/type-challenges/type-challenges/blob/main/questions/00012-medium-chainable-options/README.zh-CN.md
type Chainable<T = {}> = {
  option<K extends string, V>(key: K extends keyof T ? never : K, value: V): Chainable<Omit<T, K> & Record<K, V>>
  get(): T
}

10、最后一个元素

ts 复制代码
// https://github.com/type-challenges/type-challenges/blob/main/questions/00015-medium-last/README.zh-CN.md
type Last<T extends any[]> = T extends [...infer R, infer V] ? V : never
type Last<T extends any[]> = [never, ...T][T['length']]

评论

0条评论

logo

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