Answer the question
In order to leave comments, you need to log in
Why is Typescript showing an error?
I started to study the TS, and I can not understand why it shows an error here?
const data: {
hello: {
wtf: string
}
} = {
hello: {
wtf: 'world'
}
}
for (const [key] of Object.entries(data)) {
console.log(data[key]); // ошибка тут data[key]
}
Answer the question
In order to leave comments, you need to log in
Typescript shows an error because it types any object keys passed to Object.keys and Object.entries as strings (not string constants). This is inherent behavior. The reason the developers say is: "an object can have more properties at runtime, so the type is string[]" ( thread1 , thread2 ).
Access to the property of the object without an error in this case can be obtained only if you set the typing yourself.
The simplest solution:
const data: {
hello: {
wtf: string;
};
} = {
hello: {
wtf: 'world',
},
};
for (const [key] of Object.entries(data) as [keyof typeof data, any][]) {
console.log(data[key]);
}
interface Data {
hello: {
wtf: string;
};
}
type DataKey = keyof Data;
const data: Data = {
hello: {
wtf: 'world',
},
};
for (const [key] of Object.entries(data) as [DataKey, any][]) {
console.log(data[key]);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question