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

  1. You don't give the categoryArray constant the type Category[], because if you do the result would just be string (because Category["val"]'s type is string) 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:

  1. typeof categoryArray gets the type of categoryArray (the inferred type, since we didn't assign a specific one).
  2. [number] to access the union of types indexed by number on the type of categoryArray.
  3. ["val"] to access the union of types for the val property on the union from #2, which is the string literal type you want: "business" | "media" | "people".