'Force object properties to pick one interface key

I want to type an object which consists of several functions which all take one parameter. The problem is the typing of the parameter: Each function needs its own type and they are not compatible with each other. So, I cannot use a union type. Still, I want to type the parameter as strict as possible in the typing of the object.

My idea was to create an interface with a key for each function and then reference that in the function's definition like MyInterface["subOne"]. However, I cannot find a way to type that requirement generically in the object's typing.

This is what I've got so far:

interface MyInterface {
  subOne: {
      foo: string
  },
  subTwo: {
      bar: string
  },
  subThree: {
      dahoo: string
  }
}

const myObject: Record<"subOne" | "subTwo" | "subThree", (myParam: MyInterface) => void> = {
    subOne: (myParam: MyInterface["subOne"]) => {
        console.log(myParam.foo)
    },
    subTwo: (myParam: MyInterface["subTwo"]) => {
        console.log(myParam.bar)
    },
    subThree: (myParam: MyInterface["subThree"]) => {
        console.log(myParam.dahoo)
    }
}

The problem is the (myParam: MyInterface) part in the object's typing: How can I tell TypeScript here "The function params must pick one of the interface's keys and must not use the whole interface." Or is my attempt to solving that problem completely off and there is a better way to achieve that requirement anyway?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source