Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 551
David Nathanael Avatar asked Sep 02 '26 23:09

David Nathanael


2 Answers

You can use:

type Keys = typeof events[number]["key"]; // "clickedButton" | "clickedLink" | "clickedImage"
like image 80
Nenad Avatar answered Sep 04 '26 20:09

Nenad


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);
}
like image 24
Eugene Karataev Avatar answered Sep 04 '26 18:09

Eugene Karataev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!