When using Object.entries(), it returns the correct value types, but the keys are of type string[]
, which is incorrect. I want TypeScript to recognize my keys correctly. I attempted to use as const
on the object, but it did not have any effect.
Is there a way to assert the type in this scenario?
const demo = {
a: 'TEST',
b: 222,
} as const
Object.entries(demo)
.forEach(([key, value]) => { // key is string and not "a" | "b"
console.log([key, value])
})
// reproduce same types as above
Object.entries(demo)
.forEach(([key, value]: [string, typeof demo[keyof typeof demo]]) => {
console.log([key, value])
})
// now trying to change string to actual keys, error :(
Object.entries(demo)
.forEach(([key, value]: [keyof typeof demo, typeof demo[keyof typeof demo]]) => {
console.log([key, value])
})
// so instead trying to force somehow type assertion
Object.entries(demo)
.forEach(([key as keyof typeof demo, value]) => { // how to make assertion???
console.log([key, value])
})