My attempt to extract types of keys from nested objects led me to try the following approach.
type RecursiveRecord = {
[key in string]: string | RecursiveRecord;
};
type Keys<T extends RecursiveRecord, K = keyof T> = K extends string
? T[K] extends string
? K
: T[K] extends RecursiveRecord
? K | Keys<T[K]> // encountered an error here
: never
: never;
type Obj = {
a: {
c: 'aaaaaa';
d: 'aaaaaaaaaaa';
e: { f: 'q' };
};
b: 'dd';
};
export type A = Keys<Obj>; // expecting to retrieve "a" | "b" | "c" | "d" | "e" | "f"
However, I faced a type error with K | Keys<T[K]>
:
index.ts:9:16 - error TS2344: Type 'T[K]' does not satisfy the constraint 'RecursiveRecord'.
Type 'T[string]' is not assignable to type 'RecursiveRecord'.
Type 'string | RecursiveRecord' is not assignable to type 'RecursiveRecord'.
Type 'string' is not assignable to type 'RecursiveRecord'.