In this scenario, we have two interfaces named A and B with validation and variant properties. The goal is to create an Example object by using only the variant and validation values provided (since field is already defined). However, I encountered an error at a specific line of code highlighted below. Can someone please explain why TypeScript is throwing an error in this situation? Are there any TypeScript documentation resources that address this issue?
export interface A {
field: "Af";
variant: "A";
validation: boolean;
}
export interface B {
field: "Af";
variant: "B";
validation: number;
}
export type C = A | B;
const c: C = {
field: "Af",
variant: "A",
validation: false,
};
class Example {
private data: C;
constructor(data: C) {
this.data = data;
}
}
const test = (type: Omit<C, "field">): Example => {
const d: C = { // Error occurs here (Please explain why)
field: "Af",
...type,
};
const example = new Example(d);
return example;
};
test({ variant: "A", validation: true }); // No error expected
test({ variant: "B", validation: 1 }); // No error expected
test({ variant: "A", validation: 2 }); // Error expected
test({ variant: "B", validation: true }); // Error expected
The error message received is as follows:
Type '{ variant: "A" | "B"; validation: number | boolean; field: "Af"; }' is not assignable to type 'C'.
Type '{ variant: "A" | "B"; validation: number | boolean; field: "Af"; }' is not assignable to type 'B'.
Types of property 'variant' are incompatible.
Type '"A" | "B"' is not assignable to type '"B"'.
Type '"A"' is not assignable to type '"B"'.ts(2322)