Creating string literal union from a property in an array of objects

Viewed 97

Is it possible to get a literal string union type of a static array of object's specific property?

For example, I want to expose IconName as a type of literal strings from which is inferred from an array of objects.

I've seen it has been done to convert a read-only array to a string literal union, but not through an array of objects.

I don't think it's possible since we require some runtime interpretative functionality to access the array's values. But here's the example I'm trying to work through this svelte example https://codesandbox.io/s/svelte-typescript-forked-ef75y:

<script lang="ts">
interface Icon {
  name: string
  color: string
}

const icons: readonly Icon[] = <const>[
  {
    name: "close",
    color: "red"
  },
  {
    name: "open",
    color: "blue"
  }
];

const tuple = <K extends string[]>(...arr: K) => arr;
const iconNames = tuple(...icons.map(i => i.name));

type IconName = typeof iconNames[number];

export let name: IconName;

let displayIcon = icons.find((e) => e.name === name);
</script>


<h1>{displayIcon.color}</h1>
1 Answers

I guess the code below will do what you try to do. However, I suggest writing your type definitions in a separate file with .ts extension.

<script lang="ts">
    interface Icon {
        name: string;
        color: string;
    }

    const icons = {
        close: {
            name: "close",
            color: "red",
        },
        open: {
            name: "open",
            color: "blue",
        },
    } as const;

    type IconName = keyof typeof icons;

    export let name: IconName;

    let displayIcon = icons[name];
</script>

<h1>{displayIcon.color}</h1>
Related