如何解决限制方法签名以仅允许事件映射中定义的类型的有效负载
我正在开发一个事件(发布/订阅)系统,我需要预先定义事件和有效负载。无法将 publish
方法限制为 EVENT,EVENT[PAYLOAD]。
// This is the closest I got to,but it isn't working:
class SomeClass<EVENT_MAP,EVENTNAME extends keyof EVENT_MAP> {
publish(eventName: EVENTNAME,payload: EVENT_MAP[EVENTNAME]) {}
}
enum EVENTS {
HELLO,WORLD
}
type EVENT_SIGNATURES = {
[EVENTS.HELLO]: {
messageId: string
},[EVENTS.WORLD]: {
age: number
}
}
// This does not work as expected. What am I doing wrong?
const someClass = new SomeClass<EVENT_SIGNATURES,keyof EVENT_SIGNATURES>();
// Here's how I expect it work:
someClass.publish(EVENTS.HELLO,{ messageId: 123 }) // => error. string expected
someClass.publish(EVENTS.HELLO,{ messageId: "123",age: 15 }); // => error. age shouldn't be on here
someClass.publish(EVENTS.HELLO,{ messageId: '123' }) // => good
someClass.publish(EVENTS.WORLD,{ messageId: '123' }) // => error. messageId isn't on the type
someClass.publish(EVENTS.WORLD,{ age: 123 }) // => good
// Here's what actually happens
someClass.publish(EVENTS.HELLO,{ messageId: 123 }); // => error. string expected
someClass.publish(EVENTS.HELLO,age: 15 }); good
someClass.publish(EVENTS.HELLO,{ messageId: "123" }); // => good
someClass.publish(EVENTS.WORLD,{ messageId: "123" }); // => good
someClass.publish(EVENTS.WORLD,{ age: 123 }); // => good
这是打字稿推断的签名:
(method) SomeClass<EVENT_SIGNATURES,EVENTS>.publish(eventName: EVENTS,payload: {
messageId: string;
} | {
age: number;
}): void
而我需要将有效负载限制为 EVENTNAME。
这里还有一个沙箱:https://codesandbox.io/s/bold-joliot-1bi9m?file=/src/index.ts:591-693
提前致谢!
解决方法
尝试使发布通用,以记住传入的 eventName
:
class SomeClass<EVENT_MAP> {
publish<EVENTNAME extends keyof EVENT_MAP>(eventName: EVENTNAME,payload: EVENT_MAP[EVENTNAME]) {}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。