This problem is really testing my patience. No matter what I do, I just can't seem to make it work properly. Here's the closest I've come so far:
// Defining a complex type
type O = Record<'a', Record<'b' | 'x', Record<'c' | 'd', string | number>>>;
// Explicit way of doing it, limited to a certain depth
type Explicit = keyof O | keyof O[keyof O] | keyof O[keyof O][keyof O[keyof O]];
// A recursive method that seems promising
type ExtractKeys<T> = T extends Record<infer U, any> ?
keyof T | ExtractKeys<T[U]> :
never;
// Another approach
type ExtractKeys2<T> = T extends Record<string, any> ?
keyof T | ExtractKeys<T[keyof T]> :
never;
// Testing it out
// Error: Type instantiation is excessively deep and possibly infinite.
const tryIt: ExtractKeys<O> = 'a';
// Can assign anything without error
const tryIt2: ExtractKeys2<O> = 'z';
The issue here is clearly due to infinite recursion but I'm struggling to pinpoint exactly where the problem lies. Any suggestions on how to overcome this?