I am struggling with typing an object containing multiple functions, each taking a parameter. The issue lies in the type of the parameter: since each function requires a unique type that is not compatible with others, using a union type is not possible. However, I still want to enforce strict typing for the parameter within the object.
My initial thought was to create an interface with keys corresponding to each function and referencing it in the function definition like MyInterface["subOne"]
. Unfortunately, I have been unable to find a generic way to achieve this requirement within the object's typing.
This is my current progress:
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 challenge lies in the (myParam: MyInterface)
part of the object's typing. How can I instruct TypeScript to require that the function parameters must correspond to one of the interface's keys, rather than utilizing the entire interface?
Or perhaps there is a more effective approach to achieving this specific requirement that I am overlooking?