Closed
Description
TypeScript Version: 3.9.2
Search Terms:
discriminated union, discriminated
Code
interface OptionOne {
kind: "one";
ambiguousProperty: number; // This property name is shared, but has a different type in each unioned interface
isThisABug: boolean;
}
interface OptionTwo {
kind: "two";
ambiguousProperty: string; // This property name is shared, but has a different type in each unioned interface
prettySureThisIsABug: boolean;
}
type OptionUnion = OptionOne | OptionTwo;
// This function is riddled with errors
const myDeconstructedFunc = ({kind, ambiguousProperty, ...otherParams}: OptionUnion) => {
if (kind === "one") {
const myLocalNum: number = ambiguousProperty;
otherParams.isThisABug = true;
console.log(myLocalNum); // So this thing is used
} else if (kind === "two") {
const myLocalString: string = ambiguousProperty;
otherParams.prettySureThisIsABug = true;
console.log(myLocalString); // So this thing is used
}
};
// This function is error-free
const myNotDeconstructedFunc = (option: OptionUnion) => {
if (option.kind === "one") {
const myLocalNum: number = option.ambiguousProperty;
option.isThisABug = true;
console.log(myLocalNum); // So this thing is used
} else if (option.kind === "two") {
const myLocalString: string = option.ambiguousProperty;
option.prettySureThisIsABug = true;
console.log(myLocalString); // So this thing is used
}
};
Expected behavior:
Both of these functions have the same behavior (ideally both compiling without errors)
Actual behavior:
myDeconstructedFunc
has compile errors and can't discern the correct type inside a union isolating condition. myNotDeconstructedFunc
handles this case just fine.
Playground Link:
Link here
Related Issues:
I didn't find any that were specifically for deconstructing a shared property that was typed differently per unioned interface.