TypeScript: Boolean function inference has incorrect behavior
Bug Report
Typescript is unable to correctly determine that a function’s return satisfies the specified type.
🔎 Search Terms
“Typescript expanding boolean into true/false” (https://github.com/microsoft/TypeScript/issues/30029)
🕗 Version & Regression Information
v. 4.7.4
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about: YES
⏯ Playground Link
💻 Code
type SomeInferredFunctionType = (() => true) | (() => false);
// Gives TS error!
const test: SomeInferredFunctionType = () => {
return Math.random() > 0.5;
};
🙁 Actual behavior
Typescript thinks test does not satisfy its given type when it does. Note, that it is possible (with much difficulty) to collapse SomeInferredFunctionType into the correct simplified type() => boolean when I have direct access to the type. However, in my codebase, the type is actually automatically inferred and I do not have access to it and I am just consuming it.
🙂 Expected behavior
Typescript should be able to determine that test satisfies the condition given by SomeInferredFunctionType
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Comments: 19 (7 by maintainers)
If I say I accept
fof type() => true | () => false, then the tuple[f(), f()]must be of type[true, true] | [false, false](TS does not do this combinatorial expansion, but in principle this is what that union type means). The provided function is capable of returning[true, false]which is outside the domain of[true, true] | [false, false]Ahh yes, thank you