I’m practicing typescript but I have an issue that I doesn’t understand.
const obj = {a: 5, b: 6, c: 7}
const keys = Object.keys(obj) // string[]
The function Object.keys return string[] not the exact type.
I also try something like :
const obj = {a: 5, b: 6, c: 7}
type keys = keyof typeof obj
const keys: keys = Object.keys(obj)
But I have an issue Type 'string[]' is not assignable to type '"a" | "b" | "c"'.(2322)
I would like to use Object.keys and get the correct key value from my object
>Solution :
Hey I had the same issue and I used the following function :
const objectKeysTypedSafe = <T extends object>(obj: T) => {
return Object.keys(obj) as Array<keyof T>
}
const obj = {a: 5, b: 6, c: 7}
const keys = objectKeysTypedSafe(obj) // [a,b or c]