-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
Equality operator with unknown does not narrow the type of the unknown #25172
Comments
Related to #9999 also? |
@jcalz Not exactly, that there is a feature request, let x: unknown; // unknown always considered initialized.
if (Array.isArray(x)) {
x; // any[] (I would expect unknown[], but that's a different issue)
} else if (x instanceof Promise) {
x; // Promise<any> (again, would expect Promise<unknown> but eh)
} else if (x === true) {
x; // unknown, wat.
}
let y = String(x); // y: string, as expected
let z = Number(x); // z: number, as expected So you see, the only real "wat" here is the direct equality comparison. It's also worth noting that this behavior is consistent with |
@DanielRosenwasser |
This is especially helpful for narrowing type Response = 'yes' | 'no' | 'idk';
let validate: (x: unknown) => Response = x => (x === 'yes' || x === 'no') ? x : 'idk'; // Err: type 'unknown' is not assignable to type '"idk"' |
Accepting PRs assuming there isn't any big impact to perf or complexity |
Attempt at a PR up at #26941 |
Question: why just
|
…le-equals Fix #25172: Add narrowing for `unknown` with triple equals
TypeScript Version: 3.0.0-dev.20180623
Search Terms: typescript unknown equality guard
Code
Expected behavior:
x
inside of theif
block to be of type5
,y
to get type ofstring
, everyone happy.Actual behavior:
x
inside of theif
block is still of typeunknown
, I get an error forx
being of typeunknown
and therefore does not have a propertytoString
.Playground Link: N/A (dev build)
Related Issues: #24439
The text was updated successfully, but these errors were encountered: