是否可以将对象数组的值用作类型?
// 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"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句