Closed
Description
TypeScript Version: 3.0.0-dev.20180623
Search Terms: typescript unknown equality guard
Code
let x: unknown; // reproduces with const too
if (x === 5) {
let y = x.toString(10);
}
Expected behavior:
x
inside of the if
block to be of type 5
, y
to get type of string
, everyone happy.
Actual behavior:
x
inside of the if
block is still of type unknown
, I get an error for x
being of type unknown
and therefore does not have a property toString
.
Playground Link: N/A (dev build)
Related Issues: #24439
Metadata
Metadata
Assignees
Type
Projects
Relationships
Development
No branches or pull requests
Activity
jcalz commentedon Jun 23, 2018
Related to #9999 also?
MadaraUchiha commentedon Jun 23, 2018
@jcalz Not exactly, that there is a feature request,
unknown
can be narrowed in other ways. The following is the result on the TypeScript version mentioned at the top of this issue:So you see, the only real "wat" here is the direct equality comparison.
It's also worth noting that this behavior is consistent with
any
(That is, attempts to narrowany
with equality are met withany
as the narrowed type), but this is still rather unexpected behavior.weswigham commentedon Jun 25, 2018
@DanielRosenwasser
===
today doesn't narrow anything other than members from unions or primitives into literals today.unknown
is neither a primitive nor a union, so this is expected under our current rules, just like how{}
andany
won't be narrowed by===
, either.unknown
#25720JacksonKearl commentedon Jul 19, 2018
This is especially helpful for narrowing
unknown
to a string enummhegazy commentedon Jul 27, 2018
Similar requests in #10715, #25720, and #21732
in
operator as type guard which asserts property existence #2173217 remaining items