-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Literal type false
unexpectedly widens into type boolean
#25474
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
false
unexpectedly loosens into type boolean
false
unexpectedly widens into type boolean
Possibly related to this: function trySomething(x: number) {
if (x < 0) {
return {
result: false,
message: 'Negative numbers not allowed'
};
}
return {
result: true,
};
}
const a = trySomething(-1);
console.log(a.result ? 'Success' : `Error: ${a.message}`); The return type of If I use |
@pedro-pedrosa I don't think it's related, TS always widens literals like that unless you do something like this, which works: function trySomething(x: number) {
if (x < 0) {
return {
result: false as false,
message: 'Negative numbers not allowed'
};
}
return {
result: true as true,
};
}
const a = trySomething(-1);
console.log(a.result ? 'Success' : `Error: ${a.message}`); |
Okay that probably makes some sense, typescript probably doesn't want to make the type too strict as users of the function may want to write values to the return value of the function. |
Note that there isn't a bug with string literal types, only false/true into boolean
This works. type of |
This is an issue resulting from two separate factors:
Because the array literal declare let fa: Foo[];
declare let foo2: Foo;
fa = Array.isArray(foo2) ? foo2 : [foo2]; To fix this issue we need to propagate contextual types into spread expressions. |
false
unexpectedly widens into type boolean
false
unexpectedly widens into type boolean
Sorry, I feel like the answers I need are in this / #22596 but I can't grok it for the life of me
Is it that "true" means "boolean" if used in certain contexts to support
But I just tried that and ts seems to think that x is just true not a boolean, idk. Anyway is there anyway to have the above example work without having to use |
Uh oh!
There was an error while loading. Please reload this page.
TypeScript Version: 3.0.0-dev.20180705
Search Terms: false/true loosened/expanded/loses specificity into boolean
Code
Expected behavior:
No error.. In the else clause,
[foo2]
, it retainsstring | false
soArray<string | false>
. Logically since everything is taking place in the typings layer,foo2
should still be strongly bounded tofalse
and will never betrue
.Actual behavior:
Errors. In the else clause,
[foo2]
, it expanded/loosened tostring | boolean
soArray<string | boolean>
.Playground Link: Link
Related Issues:
The text was updated successfully, but these errors were encountered: