Closed
Description
🔎 Search Terms
"discriminated union", "refine union", "array find union property"
🕗 Version & Regression Information
Tried every TypeScript version from 5.2.2 in the playground with the same result.
I found some similar issues that eventually led me to #42384, but I wasn't sure if the root cause is the same?
⏯ Playground Link
💻 Code
interface Sharp {
// Removing 'Triangle' here to get rid of the union makes it work.
type: 'Square' | 'Triangle';
corners: number;
}
interface Round {
type: 'Circle' | 'Oval';
radius: number;
}
function getCorners(shapes: Sharp[] | Round[]) {
// Expected `Sharp | undefined` but got `Sharp | Round | undefined`
const foundSharp = shapes.find((shape) => shape.type === 'Square');
// Property 'corners' does not exist on type 'Sharp | Round'.
// Property 'corners' does not exist on type 'Round'. (2339)
return foundSharp?.corners;
}
🙁 Actual behavior
foundSharp
is Sharp | Round | undefined
even though it can never be Round
due to type
.
🙂 Expected behavior
foundSharp
should be Sharp | undefined
since only sharp shapes can have the type 'Square'.
Additional information about the issue
Setting type
in the Sharp interface to only 'Square' makes it work as expected.