2

I want to retrieve the keys from a defined object in Typescript. You can find the playground here with information on actual and expected output.

// I want users to define a variable (or const) of type A
// and then extract the keys from A

type A = {
  [key: string]: 123,
}

const aTyped: A = {
  myKey: 123,
} as const;

type ExtractKeys<T> = keyof T;

type Keys = ExtractKeys<typeof aTyped>; // expected: Keys = 'myKey'
                                        // actual value: string | number :(
Page not found
  • 2,454
  • 2
  • 10
  • 19
  • Object.keys(aTyped) should give you myKey – baliman May 02 '23 at 18:46
  • 1
    This looks the same as [this question](https://stackoverflow.com/q/76157070/2887218) so it's been linked. If you annotate as `A` then the game is over; instead you will need something like the `satisfies` operator, so you change it from `const aTyped: A = ⋯;` to `const aTyped = ⋯ satisfies A;` – jcalz May 02 '23 at 18:48
  • 1
    @jcalz Thank you, this solved my problem. To be fair, I would be completely lost without your continuous support here on SO. ;) – Page not found May 02 '23 at 19:26

0 Answers0