-
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
Type guards not working for indexed types with generics #22214
Comments
Note that |
This code is just for illustration of the compiler problem, and not any good otherwise of course. A snippet where the problem is even more obvious, without such an obvious fix: function f<T extends string>(q: {[k:string]: number | null}, t: T) {
const v= q[t];
if (v) {
const vv: number = v;
}
} Note that this fails only with strict null checks enabled. |
Narrowing with primitives really does not work with generics.. here is a simpler example: function f<T extends string | number>(t: T) {
if (typeof t !== "string") {
const v: number = t; // Error
}
} The issue here is that |
However we could totally improve our behavior and narrow to |
The problem is that this is a regression - my original example, or something equivalent to it, used to work in some earlier version (I'm not sure which exactly) because I think that this is why @mhegazy's example is different than mine, where the type does not really depend on T. |
u are correct. |
TypeScript Version: 2.7
Search Terms: indexed type guard
Code
Expected behavior:
Type of
v
isstring|number
, and in theif
it is just number. Compiles.Actual behavior:
Assignment to
vv
doesn't compile: string not assignable to number. When hovering, type ofv
is{ [k: string]: string | number; }[T]
, so eliminating string from it does not change the type, it is still the same, and only when assigning tovv
it gets resolved tostring|number
which then causes compilation error.Changing type of
t
to string fixes the problem. The problem also appears ifq
has type keyed by[k in T]
.Playground Link: link
Related Issues:
The text was updated successfully, but these errors were encountered: