My goal is to create a function that can handle various input types for abstraction purposes.
type ContentA = string
type ContentB = number
type InputA = {
name: 'method_a'
content: ContentA
}
type InputB = {
name: 'method_b'
content: ContentB
}
type Input = InputA | InputB
Each type of input corresponds to a different method:
const my_methods = {
method_a: (content:ContentA) => {
// ...
},
method_b: (content:ContentB) => {
// ...
}
}
Now I need to create a generic function that can handle all the possible inputs, as there could be many. Currently, there are only two types of inputs defined, but in my actual project, there are around 16.
I attempted to implement this kind of function, but encountered a compilation error:
function foo(input:Input){
return my_methods[input.name](input.content);
// ^
// | Argument of type 'string | number' is not
// | assignable to parameter of type 'never'.
// | Type 'string' is not assignable to type 'never'.
}
Is there a way for Typescript to understand that the argument passed to the method based on input.name
will always match with input.content
? How can I resolve this issue?