Typescript 数组对象属性值作为类型

Dav*_*ael 6 typescript typescript-typings

是否可以使用对象数组的值作为类型?

// 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);
    ...
}
Run Code Online (Sandbox Code Playgroud)

我试过这个

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

type Keys = typeof keys.values;
Run Code Online (Sandbox Code Playgroud)

等于

() => IterableIterator<"clickedButton" | "ClickedLink" | "ClickedImage">
Run Code Online (Sandbox Code Playgroud)

当我尝试使用 .find() 之后,这不起作用

难道这根本不可能吗?

Nen*_*nad 11

您可以使用:

type Keys = typeof events[number]["key"]; // "clickedButton" | "clickedLink" | "clickedImage"
Run Code Online (Sandbox Code Playgroud)