I'm encountering a slight issue with TypeScript inference on discriminated unions. Let's say I have the following types:
type TypeA = {
type: 'a';
formData: number;
onSubmit: (data: number) => void;
};
type TypeB = {
type: 'b';
formData: Date;
onSubmit: (data: Date) => void;
};
type TypeAB = TypeA | TypeB;
For simplicity, let's assume I also have a function that takes a parameter typed as the discriminated union
export const MyForm = (props: TypeAB) => {
const handleSubmit = () => {
// do other things
props.onSubmit(props.formData);
};
return "return does no matter"
};
The issue arises when calling submit as TypeScript complains that props.formData
may not match the expected type of onSubmit
https://i.sstatic.net/oxOsJ.png
However, based on the defined types, this should not be possible. onSubmit
always corresponds to the type of formData
If I check for the type before calling onSubmit, it works without any issues
const handleSubmit = () => {
// do other things
if(props.type === 'a') props.onSubmit(props.formData);
if(props.type === 'b') props.onSubmit(props.formData);
};
Nevertheless, it seems unnecessary to perform this check. Any insights on why TypeScript is raising concerns here and how to properly define the discriminated union?