For abstraction purposes I need to implement a function that accept different types of inputs.
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 input is needed for a different method:
const my_methods = {
method_a: (content:ContentA) => {
// ...
},
method_b: (content:ContentB) => {
// ...
}
}
Now I need to implement a generic function that accept all of the inputs, this is because the input types can be a lot, now there are only 2, but in my real application they are around 16.
I would like to have an implementation like this one, however it lead me to 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 infer that since I am using input.name then the argument of the method is correct - since they will always match input.name and input.content?
InputAandInputBinto classes, so you can simply add an overridable method onto them? I appreciate that this is not always possible, e.g. if they are parsed from JSON.