-
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
Narrow "string" to "keyof T" with "in" guard? #12892
Comments
yes it should as it was proven at runtime to be true (maybe not |
@Aleksey-Bykov It is actually not something that extends |
true, i always forget that unions are the other way around |
You can capture the type of export interface Map<T> {
[x: string]: T
}
interface Spec<T> {
description: string;
default: T;
}
function getDescription<S extends Map<Spec<any>>, K extends keyof S>(specs: S, k: K) {
if (k in specs) {
return specs[k].description;
// error TS2536: Type 'string' cannot be used to index type '{ [k in keyof T]: Spec<T[k]>; }'.
}
return null;
} For getting the type of default, for example, you can write it as such: function getDefault<S extends Map<Spec<any>>, K extends keyof S>(specs: S, k: K): S[K]["default"] {
if (k in specs) {
return specs[k]["default"];
// error TS2536: Type 'string' cannot be used to index type '{ [k in keyof T]: Spec<T[k]>; }'.
}
return null;
}
getDefault({ x: { description: "s", default: 1 } ,y: { description: "s", default: "ss" } }, "x"); // number
getDefault({ x: { description: "s", default: 1 } ,y: { description: "s", default: "ss" } }, "y"); // string |
The reason why narrowing is not really correct is |
Thanks for the explanation, @mhegazy |
Should
if (x in t) {}
narrow the type ofx
to bekeyof T
inside the conditional block?TypeScript Version: 2.1.4
Code
Expected behavior:
This should type check.
k
should be narrowed fromstring
tokeyof T
inside theif (k in specs)
guard.Actual behavior:
The type of
k
remainsstring
inside the guard, leading to the indexing error.The text was updated successfully, but these errors were encountered: