Skip to content

Instantly share code, notes, and snippets.

@Oaphi
Last active February 17, 2021 08:04
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 Oaphi/1c61742be865adbf1cc52d64616c438a to your computer and use it in GitHub Desktop.
Save Oaphi/1c61742be865adbf1cc52d64616c438a to your computer and use it in GitHub Desktop.
General-purpose utility types
type Invert<T> = { [ P in keyof T as Extract<T[P], string | number | symbol> ] : P };
type test1 = Invert<{ a: "ia", b: "ib", c: 1 }>; //{ ia: "a"; ib: "b"; 1: "c"; }
type DeepPath<T extends string[], U> = T extends [infer F, ...infer L]
? F extends string
? { [P in F]: L extends string[] ? DeepPath<L,U> : never }
: {}
: U;
type test2 = DeepPath<["a", "b", "c"], ()=> number>; //{ a: { b: { c: () => number } } }
//dep: type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never
type MergeUnionOfObjects<U> = { [ P in keyof UnionToIntersection<U> ] : UnionToIntersection<U>[P] };
type test3 = MergeUnionOfObjects<{a: () => string} | {b: () => number}>; //{a: () => string; b: () => number;}
type RecursiveRecord<K extends keyof any, T> = {
[ P in K ] : T | RecursiveRecord<K, T>;
}
let i : RecursiveRecord<string, string> = {
"p": {
"p": {
"o": "ok", //ok
"n": 1 //error
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment