[英]Typescript: How to use key type as enum in an object keep all enum values as optional?
[英]How to use all property values of an object as a type?
我正在尝试创建一个类来处理我的应用程序中的CustomEvent
。 这是到目前为止的样子:
export const EVENT_NAMES = {
TEST_EVENT: 'HELLO_WORLD',
THIS_IS: 'REALLY_HARD'
};
export type EventName = keyof typeof EVENT_NAMES;
export class Events {
static on(eventName: EventName, eventHandler: Function): void {
document.addEventListener(eventName, (e: CustomEvent): void => {
eventHandler(e.detail);
});
}
}
/*
Want to do this, but TypeScript complains:
Argument of type 'string' is not assignable to parameter of type
'"TEST_EVENT" | "THIS_IS"'. ts(2345)
*/
Events.on(EVENT_NAMES.TEST_EVENT, () => {
// handle the event
});
我想强制传递给Events.on
eventName
参数的任何值都是属于EVENT_NAMES
的有效事件,它是该对象中任何属性的值,而不是任何道具的键。 我不太清楚如何实现这一点,如果有人有任何指示,那将不胜感激!
首先,您对EventName
的定义将您设置为使用来自EVENT_NAMES
的键作为参数,而不是值。 其次,值的类型是字符串。 您可以使用as
来投射那些:
const EVENT_NAMES = {
TEST_EVENT: 'HELLO_WORLD',
THIS_IS: 'REALLY_HARD'
} as const;
// 'HELLO_WORLD' | 'REALLY_HARD'
export type EventName = typeof EVENT_NAMES[keyof typeof EVENT_NAMES];
现在,这应该有效:
Events.on(EventNames.HELLO_WORLD, () => {});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.