简体   繁体   中英

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' type t = 'n1' | 'n2' | 'n3' type t = 'n1' | 'n2' | 'n3' from array a , is it possible in typescript?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM