My object is discriminated based on the type
property, which can be any value from a specified enum. I encounter an issue in TypeScript when passing a valid object to a function; it complains about mismatched types. However, coercing the enum value resolves the issue.
enum AorB {
A = 'a',
B = 'b',
};
type Bar_A = {
type: AorB.A;
};
type Bar_B = {
type: AorB.B;
}
type Bar = Bar_A | Bar_B;
function foo(a: Bar): void {}
const arg = {
type: AorB.A,
};
// this would work but is extra writing
// const arg = {
// type: AorB.A as AorB.A
// };
foo(arg); // Error
foo({
type: AorB.A,
})
For a similar scenario, you can check out the corresponding playground link