I am trying to refactor some code where a function returns a different type of content based on the key I pass in, and I need to put together a function signature that will be able to accept different types of content based on what key it is.
A simpler example that demonstrates my issue is the following:
type OptionA = { type: 'A'; val: number };
type OptionB = { type: 'B'; val: string };
type Option = OptionA | OptionB;
function give<T extends Option['type']>(type: T, val: Extract<Option, { type: T }>['val']) {
take({ type, val });
}
function take(o: Option) {
console.log(o);
}
This code to me seems to have no possible typing issues as the only ways to use the give
function are as such:
give('A', 1) // No error
give('B', 'a') // No error
give('A', 'a')
// Warning: Argument of type 'string' is not assignable to parameter of type 'number'.ts(2345)
give('B', 1)
// Warning: Argument of type 'number' is not assignable to parameter of type 'string'.ts(2345)
How could I possibly update the function type signature to remove this warning?