You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When using type guard on unknown to narrow down a type, we can safely make assertions about an object, but the type information does not carry down for editor hints.
functionhasProp<Propextendsstring|number|symbol>(value: unknown,prop: Prop): value is Record<Prop,unknown>{if(typeofvalue!=='object'){returnfalse;}if(!value){returnfalse;}returnpropinvalue;}declareconsttest: unknown;if(hasProp(test,"foo")&&hasProp(test.foo,"bar")&&typeoftest.foo.bar==="boolean"){test.foo.bar;// ^? — this is typed as Record<"foo", unknown> when we actually know more info than it is telling us}
🙁 Actual behavior
When hovering over test or using the // ^? syntax, it's visible that test is of type Record<'foo', unknown>, when really we have already asserted that there is more type information there available to us (e.g. .foo.bar` which is a boolean)
🙂 Expected behavior
The correct shape would appear, e.g.
consttest: {foo: {bar: boolean}}
The text was updated successfully, but these errors were encountered:
alii
changed the title
Using Type guard provide incorrect editor hints
Type guard on unknown provides incorrect or "stale" editor hints
May 13, 2022
All three of test, test.foo and test.foo.bar are narrowed correctly. The fact that test doesn't become { foo: { bar: boolean } } is expected - in general once you've arrived at Record<K, unknown> (whatever K happens to be), you can't infer anything further about its value type just by checking its individual properties. To put it another way, Record<K, string | number> doesn't suddenly become Record<K, string> just because you can't find any numbers in it right now.
Also, type guards on object properties never narrow the parent object in TS except in the case of discriminated unions. See #31755.
Bug Report
When using type guard on
unknown
to narrow down a type, we can safely make assertions about an object, but the type information does not carry down for editor hints.🔎 Search Terms
type, guard, editor, hint, incorrect, inlay
🕗 Version & Regression Information
⏯ Playground Link
Playground link with relevant code
💻 Code
🙁 Actual behavior
When hovering over
test
or using the// ^?
syntax, it's visible thattest
is of typeRecord<'foo', unknown>
, when really we have already asserted that there is more type information there available to us(e.g.
.foo.bar` which is a boolean)🙂 Expected behavior
The correct shape would appear, e.g.
The text was updated successfully, but these errors were encountered: