Description
Bug Report
🔎 Search Terms
both sides conditional type assignable
🕗 Version & Regression Information
- This changed for the better between versions 4.2.3 and 4.3.5 and back between 4.4.4 and 4.5.5
- Nightly version at time of testing: v5.0.0-dev20221111
⏯ Playground Link
Playground link with relevant code
💻 Code
const demo = function<B extends boolean>(
myBool: B,
definedValue?: string
) {
//Error ts(2322): Type 'undefined' is not assignable to type
//'B extends false ? undefined : string | undefined'.
let keyValue : (B extends false ? undefined : (string | undefined)) = undefined;
if(myBool) {
keyValue = definedValue;
}
}
const tinyDemo = function<B extends boolean>(myBool: B) {
//Error ts(2322): Type 'number' is not assignable to type 'B extends true ? number : number'.
let myVar : (B extends true ? number : number) = 5;
}
🙁 Actual behavior
Errors as noted, plus one on the conditional assignment in the first example.
🙂 Expected behavior
If a variable has a conditional type but type T
is on both sides of the conditional, I should be able to assign type T
to that variable regardless of which branch of the conditional applies.
Cross-links
#30639 is an older PR which claims to fix an issue that sounds a lot like this, and that was merged 3/11/21 - it looks like that was for 4.3 which changed things for the better. Restoring that fix might be a step in the right direction. (There is still an error in the conditional assignment, where the conditional type should be narrowable to allow that assignment, but that might be separable as a different issue.)
#46429 is another PR merged over a year ago, just ahead of version 4.5. The issue reappeared somewhere in the 4.5 range, so it's possible that this PR was the cause of the regression. The issue still exists in the latest version.
In some cases, where the types on each side of the conditional are complex constructed types, it might be harder to figure out if T
is in fact assignable to both sides of the conditional. However, these examples use primitives, so that's clearly not the source of the issue.