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
I would expect the following code to typecheck and work:
const x = { a : 1, b : 2 };
for (const foo in x) {
console.log(x[foo]);
}
However, it gives an error that x has no index signature.
The problem appears to be that foo is not inferred to be of type keyof (typeof x). If I do the following, there are no errors:
const x = { a : 1, b : 2 };
for (const foo in x) {
console.log(x[foo as keyof (typeof x)]);
}
Shouldn't x be inferred to be that type?
(Apologies if this issue already exists somewhere. I searched pretty hard and I could not find it.)
It also seems weird that something like this infers the type of foo properly. We have less information about x, yet our type constraint on x is stricter.
function test<T>(x: T) {
for (const foo in x) {
console.log(x[foo]);
}
}
The text was updated successfully, but these errors were encountered:
Ah, that's pretty tough for something which developers do all the time.
Are there any workarounds for iterating over and indexing an object in a typesafe manner? One I see is to give all my types index signatures, but I have a habit of defining object literals and allowing the type inference to take over.
any (non-strict) or { [k: string]: { } } (strict) are the types you should assert x to in this case.
Since we don't know (in general) that x doesn't actually reference a subtype with other keys of different types, there's no known-correct type for us to produce for x[k] in a for(k in x).
I would expect the following code to typecheck and work:
However, it gives an error that
x
has no index signature.The problem appears to be that
foo
is not inferred to be of typekeyof (typeof x)
. If I do the following, there are no errors:Shouldn't
x
be inferred to be that type?(Apologies if this issue already exists somewhere. I searched pretty hard and I could not find it.)
It also seems weird that something like this infers the type of
foo
properly. We have less information aboutx
, yet our type constraint onx
is stricter.The text was updated successfully, but these errors were encountered: