6

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?

2 Answers 2

11

You can use:

type Keys = typeof events[number]["key"]; // "clickedButton" | "clickedLink" | "clickedImage"
Sign up to request clarification or add additional context in comments.

1 Comment

use as const satisfies readonly <your_type_here> to verify the type when assigned a const. satisfies was added in TS 4.9
2

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.