Get string literal types from Array of objects
You can do it if:
-
The values in the array don't change at runtime (since type information is a compile-time-only thing with TypeScript); and
-
You tell TypeScript that they values won't change by using
as const
; and
- You don't give the
categoryArray
constant the typeCategory[]
, because if you do the result would just bestring
(becauseCategory["val"]
's type isstring
) rather than the string literal union type you want.
Here's an example (playground link):
export interface Category{
val: string;
icon: string
}
const categoryArray = [
{
val: 'business',
icon: 'store'
},
{
val: 'media',
icon: 'video'
},
{
val: 'people',
icon: 'account'
},
] as const;
type TheValueUnion = (typeof categoryArray)[number]["val"];
// ^? −− "business" | "media" | "people"
The key bits there are the as const
and type TheValueUnion = (typeof categoryArray)[number]["val"];
, which breaks down like this:
-
typeof categoryArray
gets the type ofcategoryArray
(the inferred type, since we didn't assign a specific one). -
[number]
to access the union of types indexed by number on the type ofcategoryArray
. -
["val"]
to access the union of types for theval
property on the union from #2, which is the string literal type you want:"business" | "media" | "people"
.