-
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
Typescript should be able to derive the type of the array created by Object.keys
from the key signature of the object
#28284
Comments
Duplicate of #26901 (any many others). |
@ahejlsberg thanks for the additional context. If this isn't possible, could someone at least explain or link to what is the most idiomatic typescript in these situations? |
@quinn If you are certain type Keys = 'one' | 'two';
const obj:{[key in Keys]: string} = {
one: 'value for one',
two: 'value for two',
};
Object.keys(obj).forEach(key => console.log(obj[key as Keys]));
(Object.keys(obj) as Keys[]).forEach(key => console.log(obj[key])); |
@ahejlsberg using |
and I definitely feel like i'm not doing something right if i ever need to use |
Emmm, same problem with let a: ClassA;
for (let k in a) {
console.log(a[k]); // [ts] Element implicitly has an 'any' type because type 'ClassA' has no index signature. [7017]
} And must be written in this style: let a: ClassA;
let k: keyof ClassA;
for (k in a) {
console.log(a[k]); // That's okay.
} So, why doesn't TS give |
So let's say you write const obj = { x: 1, y: 2 };
It would be bad if TypeScript allowed a value type Point = { x: number, y: number };
function fn(x: Point) {
// Proposal: make this *not* an error
for (let k in x) printXorY(k);
}
function printXorY(key: keyof Point) {
switch(key) {
case "x":
console.log("is x");
break;
case "y":
console.log("is y");
break;
default:
throw new Error("HOW IS THIS HAPPENING");
}
}
const p3 = { x: 1, y: 2, z: 3 };
fn(p3); // oops |
TypeScript Version: 3.2.0-dev.201xxxxx
Search Terms:
object.keys
Code
Expected behavior:
No error.
Actual behavior:
Playground Link:
Related Issues:
The text was updated successfully, but these errors were encountered: