Skip to content

Instantly share code, notes, and snippets.

@danieldietrich
Last active October 7, 2022 02:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danieldietrich/91784d1c0c4e3dea67ea85098c0ea5e0 to your computer and use it in GitHub Desktop.
Save danieldietrich/91784d1c0c4e3dea67ea85098c0ea5e0 to your computer and use it in GitHub Desktop.
Traverse the type of an object tree, find leafs that are function types and collect the type of their first argument.
class C {}
const obj = {
a: {
x: {
y: () => 1
}
},
b: {
c: ({b}: { b: boolean }) => b // { b: boolean }
},
c: () => new C(),
n: ({n}: { n: number }) => n, // { n: number }
s: ({s}: { s: string }) => s, // { s: string }
xxx: ({b}: { b: string }) => b // { b: string }
}
// ✅
// type Test = {
// b: never, // <-- merge conflict, { b: boolean } & { b: string } = { b: never }
// n: number,
// s: string
// }
type Test = Reflect<typeof obj>;
type Reflect<T> = T extends Record<PropertyKey, unknown>
? MergeObjects<FunctionArgs<PickByValue<T, (...args: any[]) => any>>, Reflect<UnionToIntersection<Values<PickByValue<T, Record<PropertyKey, unknown>>>>>>
: unknown;
type Merge<S, T> =
Or<Is<S, never>, Is<T, never>> extends true ? never :
Or<Is<S, any>, Is<T, any>> extends true ? any :
Or<Is<S, unknown>, Is<T, unknown>> extends true ? unknown :
S extends Record<PropertyKey, unknown>
? T extends Record<PropertyKey, unknown> ? MergeObjects<S, T> : never
: T extends Record<PropertyKey, unknown> ? never : (S extends T ? S : never);
type MergeObjects<S, T> =
Union<{
[K in keyof S | keyof T]: K extends keyof S
? (K extends keyof T ? Merge<S[K], T[K]> : S[K])
: (K extends keyof T ? T[K] : never)
}>;
type Is<T1, T2> = (<T>() => T extends T2 ? true : false) extends <T>() => T extends T1 ? true : false ? true : false;
type Or<C1 extends boolean, C2 extends boolean> = C1 extends true ? true : C2 extends true ? true : false;
type FunctionArgs<T> = T[keyof T] extends (arg0: infer A) => any ? A : never;
type PickByValue<T, V> = Pick<T, { [K in keyof T]-?: T[K] extends V ? K : never }[keyof T]>;
type Union<T> = T extends Record<PropertyKey, unknown> ? { [K in keyof T]: T[K] } : T;
type UnionToIntersection<U> = (U extends any ? (arg: U) => void : never) extends ((arg: infer I) => void) ? I : never
type Values<T> = T[keyof T];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment