14

Object.keys() as const not working. How can I achieve this? (Suppose I don't know the content of the object, I don't know what keys does my object have)

const values = Object.keys(myObject) as const;

I need the as const to get string literal types

let name: typeof values[number];
Bruno Pintos
  • 363
  • 3
  • 10

1 Answers1

15

You can do

let name: keyof typeof myObject

See this question for why strongly typing Object.keys might be a bad idea.

Rubydesic
  • 3,386
  • 12
  • 27
  • 1
    this doesn't work if MyObject has type of an index signature. for example: type MyObject = { [key: string]: string; }; const obj: MyObject = { name: 'John', age: "age", }; – XWZ Mar 04 '23 at 01:58