Skip to content

Instantly share code, notes, and snippets.

@waki285
Created May 7, 2022 03:36
Show Gist options
  • Save waki285/186670e74e2f33b03d3aea64dc2b9990 to your computer and use it in GitHub Desktop.
Save waki285/186670e74e2f33b03d3aea64dc2b9990 to your computer and use it in GitHub Desktop.
Utility Types Polyfill
import { Expect, Equal } from "@type-challenges/utils"
type MyPick<T extends object, K extends keyof T> = { [P in K]: T[P] };
type MyOmit<T extends object, K extends keyof T> = { [P in Exclude<keyof T, K>]: T[P] };
type MyPartial<T extends object> = { [P in keyof T]?: T[P] };
type MyRequired<T extends object> = { [P in keyof T]-?: T[P] };
type MyReadonly<T extends object> = { readonly [P in keyof T]: T[P] };
type MyRecord<K extends string | number | symbol, V> = { [P in K]: V };
type MyExclude<T, U> = T extends U ? never:T;
type MyExtract<T, U> = T extends U ? T:never;
type MyNonNullable<T> = T extends null | undefined ? never:T;
type MyParameters<T extends (...args: any) => unknown> = T extends (...args: infer P) => unknown ? P:never;
type MyReturnType<T extends (...args: any) => unknown> = T extends (...args: any) => infer U ? U: never;
type Example = { a: "b", c: 1, d: true };
type Example2 = { a: "b", c: 1, d?: true };
type Example3 = string | number | true | null;
type Example4 = (arg1: string, arg2: number) => boolean;
type Cases = [
Expect<Equal<MyPick<Example, "a" | "d">, Pick<Example, "a" | "d">>>,
Expect<Equal<MyOmit<Example, "c">, Omit<Example, "c">>>,
Expect<Equal<MyPartial<Example2>, Partial<Example2>>>,
Expect<Equal<MyRequired<Example2>, Required<Example2>>>,
Expect<Equal<MyReadonly<Example2>, Readonly<Example2>>>,
Expect<Equal<MyRecord<string, number>, Record<string, number>>>,
Expect<Equal<MyExclude<Example3, string | true>, Exclude<Example3, string | true>>>,
Expect<Equal<MyExtract<Example3, string | true>, Extract<Example3, string | true>>>,
Expect<Equal<MyNonNullable<Example3>, NonNullable<Example3>>>,
Expect<Equal<MyParameters<Example4>, Parameters<Example4>>>,
Expect<Equal<MyReturnType<Example4>, ReturnType<Example4>>>,
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment