Home > Blockchain >  keyof only exist property
keyof only exist property

Time:07-05

i have a next type

type Data = {
 foo: {
   foo_id: number;
 };
 bar: undefined;
 abc: {
   abc_id: number
 }
};

I need to get array of nested keys, if they exist, and ignore undefined values: 'foo_id' | 'abc_id'[]

CodePudding user response:

You can use a recursive self-indexing mapped type:

type Data = {
  foo: {
    foo_id: number;
  };
  bar: undefined;
  abc: {
    abc_id: number
  }
};

type NestedKeys<T extends object> = {
    [K in keyof T]: T[K] extends undefined ? never :
                    T[K] extends object ? NestedKeys<T[K]> : K
}[keyof T];

type X = NestedKeys<Data>[];

const x: X = ['foo_id', 'abc_id'];

Playground link

  • Related