gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:56:57 25 4
gpt4 key购买 nike

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

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

我试过了

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

type Keys = typeof keys.values;

等于

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

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

这不可能吗?

最佳答案

你可以使用:

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

关于Typescript 数组对象属性值作为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61327215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com