how to get child type of a interface in ts

i'm trying to do something like a EventBus, now i've put all event names and event parameters in one interface like this:

interface A {
   a: {
      x: number
      y: number
   b: {
      name: string
function on<T extends keyof A>(evName: T, cb: (ev, param: A[T]) => void) {}

it's ok to write callback function like:

on('a', (ev, param) => {})

in this part of code, param has a certain and correct type of { x: number, y: number }, but when i try to write the callback function in another file like:

// file 1
on('a', doA)

// file 2
export const doA: (ev, params: ?) = (ev, params) => {}

i don't know how to declare the type of function doA()


  • You can use an indexed access type of the form ObjType[KeyType] even if the KeyType is a literal type like "a" and not a generic type parameter. For your example, you could just write A["a"] which evaluates to {x:number; y: number}:

    const doA: (ev: any, params: A["a"]) => void =
      (ev, params) => { }
      //   ^? (parameter) params: { x: number; y: number; }
    on('a', doA); // okay

    Playground link to code