David Nathanael
David Nathanael

Reputation: 105

Typescript array object property value as type

Is it possible to use values of an array of object as a type?

// this array is static
export const events = [
    {
        id: 1,
        key: 'clickedButton',
    },
    {
        id: 2,
        key: 'clickedLink',
    },
    {
        id: 3,
        key: 'clickedImage',
    },
] as const;

type Keys = //<-- How do I get this to : "clickedButton" | "ClickedLink" | "ClickedImage"

const dispatchEvent(key: Keys) => {
    const event = events.find(e => e.key === key);
    ...
}

I tried this

const keys = events.map((e) => e.key);

type Keys = typeof keys.values;

equals

() => IterableIterator<"clickedButton" | "ClickedLink" | "ClickedImage">

which doesnt work when I try to use .find() after

Is it simply impossible?

Upvotes: 6

Views: 2663

Answers (2)

Nenad
Nenad

Reputation: 26727

You can use:

type Keys = typeof events[number]["key"]; // "clickedButton" | "clickedLink" | "clickedImage"

Upvotes: 11

Eugene Karataev
Eugene Karataev

Reputation: 1971

A possible solution is to refactor your code with enums.

enum Keys {
    clickedButton = 'clickedButton',
    clickedLink = 'clickedLink',
    clickedImage = 'clickedImage'
}

// this array is static
export const events = [
    {
        id: 1,
        key: Keys.clickedButton,
    },
    {
        id: 2,
        key: Keys.clickedLink,
    },
    {
        id: 3,
        key: Keys.clickedImage,
    },
] as const;

const dispatchEvent = (key: Keys) => {
    const event = events.find(e => e.key === key);
}

Upvotes: 2

Related Questions