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