I wanted to extract types of keys of nested objects and tried something like the below.
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]> // here I got error
: never
: never;
type Obj = {
a: {
c: 'aaaaaa';
d: 'aaaaaaaaaaa';
e: { f: 'q' };
};
b: 'dd';
};
export type A = Keys<Obj>; // want to get "a" | "b" | "c" | "d" | "e" | "f"
But on the K | Keys<T[K]>, I got the following type error.
Is there any clean way to solve this?
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'.