繁体   English   中英

如何使用对象的所有属性值作为类型?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM