2

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.

4
  • ...did you try it? Commented Mar 31, 2020 at 7:12
  • Haha, did you? It will give you a type with "0" | "1" | "2" | "length" | "push" etc... I need the values not the keys. Commented Mar 31, 2020 at 7:15
  • If you do keyof typeof it will, yes. They're the keys of the array type. Your question just shows an ellipsis, though; it's helpful to put what you've tried and what happened. Commented Mar 31, 2020 at 7:16
  • Thanks, but the ellipsis was meant to indicate that I didn't have a clue :) Commented Mar 31, 2020 at 7:19

1 Answer 1

6

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"
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.