>>106010463I suspect the performance issue is real, I do not know how easy it would be to optimize it for JS engines.
As for common fields, they can be used as is, if the type is the same or the usage is compatible with whatever the union (not tagged union, type union) has.
type A = {
kind: "a";
value: string;
dissimilar_value: number;
}
type B = {
kind: "b";
value: string;
dissimilar_value: {x: number; y: number;};
}
type TU = A | B;
const tu: TU =
false
?
{
kind: "a",
value: "some value",
dissimilar_value: 16,
}
:
{
kind: "b",
value: "other value",
dissimilar_value: {x: 3, y: 4},
};
console.log("value : " + tu.value);
// Fails to compile:
// Operator '+' cannot be applied to types 'number | { x: number; y: number; }' and 'number'.
//console.log("dissimilar_value + 5 : " + (tu.dissimilar_value + 5));
// Fails to compile:
// Property 'x' does not exist on type 'number | { x: number; y: number; }'.
// Property 'x' does not exist on type 'number'.
//console.log("dissimilar_value.x + 7 : " + (tu.dissimilar_value.x + 7));
switch (tu.kind) {
case "a": {
console.log("dissimilar_value + 5 : " + (tu.dissimilar_value + 5));
break;
}
case "b": {
console.log("dissimilar_value.x + 7 : " + (tu.dissimilar_value.x + 7));
break;
}
}