0

I know that in Typescript you can do this:

const someOptions = {
  a: "",
  b: "",
  c: ""
} as const 


type SomeType = keyof typeof someOptions

I would like to do something very similar but then using an array as input.

const someOptions = ["a", "b", "c"] as const;
type SomeType = ...

Is this possible?

An array is convenient because I can pass it directly to something like Joi.string().valid(). Also, I also don't have sensible values to define for these things in a key/value object so it feels silly to use an object as starting point.

Thijs Koerselman
  • 21,680
  • 22
  • 74
  • 108

1 Answers1

4

You can access [number] on the typeof someOptions array to get to the values as a union type:

const someOptions = ["a", "b", "c"] as const;
type SomeType = typeof someOptions[number]
// SomeType is:
// "a" | "b" | "c"
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320