languanghao
languanghao

Reputation: 1

Is it possible to define a type from an array object in typescript

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?

Upvotes: 0

Views: 34

Answers (1)

Nick
Nick

Reputation: 16586

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.

Upvotes: 4

Related Questions