Repository navigation
Inconsistent boolean literal typesΒ #48363
Description
Activity
MartinJohns commented
on Mar 21, 2022 ContributorMore actionsRelated: #48150
ahejlsberg commented
on Mar 21, 2022 MemberAuthorMore actionsThe issue here is that when a boolean literal (
falseortrue) is contextually typed by typeboolean, we don't widen the type of the literal toboolean. This is inconsistent with our behavior for string, number and bigint literals which are widened when their contextual type isstring,numberorbigint, respectively. The difference comes from the fact thatbooleanis just an alias for the union typefalse | true, whereasstring,number, andbigintaren't (infinite) unions of literals, but rather distinct primitive types.This issue was discussed in #48150 and before that here. It definitely seems odd and inconsistent. We'd be better off considering the contextual type
booleanakin tostring,number, andbigintfor purposes of widening literals. I know we tried that in the past and one issue was abooleancontextual type arising from separatefalseandtruetypes as discriminants. For example:let x: { kind: false, x: number } | { kind: true, x: string } = { kind: false, x: 42 };
Here, at least in the past, the
kindproperty in the object literal would have the contextual typeboolean(the union offalseandtrue). However, these days we discriminate the contextual type by discriminant properties in the object literal, thus removing the{ kind: true, x: string }variant, and therefore the contextual type is justfalse. And thus we wouldn't widen.I'm going to put up a PR to see what the effects are.
Reacted by Elias Skogevall, Ryan Cavanaugh and StΓ©phane Le Dorze- addedFix AvailableA PR has been opened for this issueA PR has been opened for this issue
on Mar 23, 2022 - locked as resolved and limited conversation to collaborators
on Oct 22, 2025
π Version & Regression Information
This is the behavior in every version I tried.
β― Playground Link
Playground link with relevant code
π» Code
π Actual behavior
Error on
bb2is surprising and inconsistent with lack of error onbn2.π Expected behavior
Expected the
box(false)expression to have typeBox<boolean>for bothbb1andbb2.