Jacky Lau
Jacky Lau

Reputation: 733

how can i refer to the children of generic type

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?

Upvotes: 0

Views: 118

Answers (1)

Tobias S.
Tobias S.

Reputation: 23865

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

Upvotes: 2

Related Questions