0

I have an array

const a = [
  {
     name: 'n1',
     text: 't1',
  },
  {
     name: 'n2',
     text: 't2',
  },
  {
     name: 'n3',
     text: 't3',
  },
]

I want to define a type type t = 'n1' | 'n2' | 'n3' from array a, is it possible in typescript?

1 Answer 1

4

If you define your array with a const assertion (as const) then you can use typeof a[number]["name"]:

const a = [
  {
     name: 'n1',
     text: 't1',
  },
  {
     name: 'n2',
     text: 't2',
  },
  {
     name: 'n3',
     text: 't3',
  },
] as const;

type Names = typeof a[number]["name"];

Here is a working repl with the type definition.

Sign up to request clarification or add additional context in comments.

1 Comment

Is there a way to apply 'as const' after the fact, like on the same statement as the typeof ( it doesn't seem to work, but I'm wondering if there is a workaround for that if you can't modify the original data) ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.