Home > Software design >  how can i refer to the children of generic type
how can i refer to the children of generic type

Time:08-19

I would like to have a general type checking on the keys of provided object and its children. here is the idea:

type A<T> = {
  key: keyof T;
  childKey: keyof T[this.key] // i dont know how to make this work
};

if the above type works:

const a = {  child1: { param: 1 }, child2: { param: 1 } };


const myObj: A<typeof a> = {
  key: "child3",        // << child3 is not a key of a
  childKey: "param"
}

const myObj: A<typeof a> = {
  key: "child1",        
  childKey: "param2"    // << param2 is not a key of a.child1
}

i tried keyof T[this.key], keyof T["key"], keyof ThisType["key], none of them are giving me correct behvaiour. Can someone gives me suggestion?

CodePudding user response:

If I understand you correctly, you probably want to create a union of all valid key and childKey combinations. This can be done by mapping over the keys and nested keys.

type A<T> = {
   [K1 in keyof T]: {
      [K2 in keyof T[K1]]: {
         key: K1,
         childKey: K2
      }
   }[keyof T[K1]]
}[keyof T]

const myObj: A<typeof a> = {
  key: "child3",        // Type '"child3"' is not assignable to type '"child1" | "child2"'
  childKey: "param"
}

const myObj2: A<typeof a> = {
  key: "child1",        
  childKey: "param2"    // Type '"param2"' is not assignable to type '"param"'
}

Playground

  • Related