Description
Bug Report
In cases with discriminant unions that don't fit the conventional form (e.g. one property that's constant among all union members) type discrimination doesn't happen as one might expect or desire, see the code example.
I tried to search to see if this had been talked about before, but couldn't find anything. I imagine the current design was around capturing a common pattern in js while not spending too much time trying to narrow the types.
To address this in the same framework: discriminateTypeByDiscriminableItems
and isDiscriminantProperty
would have to be tweaked to handle missing properties and it's not clear how that would work with exactOptionalPropertyTypes
. Alternatively, the existing code may work by first filtering the union down to feasible assignments based on the exitance of properties, e.g. only consider types that the object literal has every non-optional property. However, doing that correctly would require constructing a filtered union type and I'm not sure if there's precedent for that.
Doing any of this will likely cause a performance penalty, so I think it's also fair to say this pattern is infrequent enough to not care about getting correct.
🔎 Search Terms
discriminant unions narrowing
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about 3.3
⏯ Playground Link
Playground link with relevant code
💻 Code
type DiscriminatorA = {
a: true;
cb: (x: string) => void;
}
type DiscriminatorB = {
b: true;
cb: (x: number) => void;
}
declare function f(options: DiscriminatorA | DiscriminatorB): void;
f({
b: true,
cb: n => n.toFixed()
});
🙁 Actual behavior
Parameter 'n' implicitly has an 'any' type.(7006)
🙂 Expected behavior
type checks successfully