You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
type FailedTest = { status: '1' | '3' } | FailedTestSpecial
type FailedTestSpecial = { status: '2', data: '2' }
const FailedInput = [] as Array<FailedTest>
const FailedOutput = [] as Array<FailedTestSpecial>
if (FailedInput[0].status == '1' || FailedInput[0].status == '3') {
FailedInput[0].data // This works as exected.
} else {
FailedInput[0].status
FailedOutput.push(FailedInput[0])
}
// Declared now as status 1 and 3 separately
type PassedTest = { status: '1' } | PassedTestSpecial | { status: '3' }
type PassedTestSpecial = { status: '2', data: '2' }
const passedInput = [] as Array<PassedTest>
const passedOutput = [] as Array<PassedTestSpecial>
if (passedInput[0].status == '1' || passedInput[0].status == '3') {
passedInput[0].data // This works as exected.
} else {
passedInput[0].status
passedOutput.push(passedInput[0])
}
π Actual behavior
In the failed test, at else in the if block, Typescript understands the status key could only be '2' (mouse hover over .status shows the info), but could not infer from this that the type must be FailedTestSpecial type.
In the passed test, with only the change in how PassedTest is defined by separating {status: '1' | '3'} to {status: '1'} | {status: '3'}, Typescript can now tell the discriminated union in if block.
π Expected behavior
FailedTest to pass, by inferring the type must be FailedTestSpecial type.
The text was updated successfully, but these errors were encountered:
Discord for Typescript tells me that type FailedTest = { status: '1' | '3' } | FailedTestSpecial will not form a discriminated union and only the other way is the correct way to form it.
If this is the case, then I guess this isn't a bug. But in my mind this is very unintuitive, as Typescript is clearly able to infer that only one status code is possible in the else block.
Perhaps this can be turned into a feature suggestion, if this behaviour is not a bug?
Bug Report
π Search Terms
Discriminated union, if, if condition, conditional statements
π Version & Regression Information
4.4.4
β― Playground Link
Playground Link
π» Code
π Actual behavior
In the failed test, at
else
in the if block, Typescript understands the status key could only be '2' (mouse hover over.status
shows the info), but could not infer from this that the type must beFailedTestSpecial
type.In the passed test, with only the change in how
PassedTest
is defined by separating{status: '1' | '3'}
to{status: '1'} | {status: '3'}
, Typescript can now tell the discriminated union in if block.π Expected behavior
FailedTest to pass, by inferring the type must be
FailedTestSpecial
type.The text was updated successfully, but these errors were encountered: