incorrect type using keyof and for..in #49882
Labels
Awaiting More Feedback
This means we'd like to hear from more people who would be helped by this feature
Suggestion
An idea for TypeScript
Bug Report
It's possible to declare a key variable as a
keyof
before afor..in
loop with no errors (even with strict mode enabled), even though it takes on values outside of that type.For example in the following code,
key
is able to have the typekeyof A
even though it takes on other values:If you remove the
keyof A
type annotation, thenkey
has the correct typestring
.If you try using other incorrect types, such as
let key: 'z';
orlet key: number;
then the errorThe left-hand side of a 'for...in' statement must be of type 'string' or 'any'. (2405)
correctly appears. So it seems wrong to me that only this particular incorrect type is allowed.Also, this behavior disagrees with how the types of
Object.keys()
(discussed in #12253) andfor..in
(discussed in #12314) intentionally avoid the mistake of havingkeyof
types.🔎 Search Terms
keyof, for..in, key type
🕗 Version & Regression Information
⏯ Playground Link
Playground link with relevant code
💻 Code
🙁 Actual behavior
for (key in a) {
does not have a type error🙂 Expected behavior
for (key in a) {
should have the errorThe left-hand side of a 'for...in' statement must be of type 'string' or 'any'. (2405)
, as it does for other incorrect types.The text was updated successfully, but these errors were encountered: