Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Object keys doesn't infer key value correctly

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]

code source

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading