json-rules-engine
json-rules-engine copied to clipboard
fix: Updated engine on overload to include generic option
Problem:
When directly subscribing to an emitted event through the engine's on method, the parameter types for the callback function do not match the types of the parameters at runtime. This leads to compilation errors when directly subscribing to events.
// subscribe directly to the 'young-adult' event
engine.on('young-adult-rocky-mnts', (params) => {
// params: {
// giftCard: 'amazon',
// value: 50
// }
// Should work!
engine.on('young-adult-rocky-mnts', ({ giftCard, value }) => { // Property 'value' does not exist on type 'Event'.
console.log(`I got an ${giftCard} card with $${value}!`)
})
});
index.ts:60:40 - error TS2339: Property 'giftCard' does not exist on type 'Event'.
60 engine.on('young-adult-rocky-mnts', ({ giftCard, value }) => { // Property 'value' does not exist on type 'Event'.
index.ts:60:50 - error TS2339: Property 'value' does not exist on type 'Event'.
60 engine.on('young-adult-rocky-mnts', ({ giftCard, value }) => { // Property 'value' does not exist on type 'Event'.
Solution:
By updating the EventHandler declaration to make use of an optional generic and by providing a generic overload to the on method, users can provide their own typings for the shape of the event emitted.
export type EventHandler<T = Event> = (
event: T,
almanac: Almanac,
ruleResult: RuleResult
) => void;
on(eventName: "success", handler: EventHandler): this;
on(eventName: "failure", handler: EventHandler): this;
on<T>(eventName: string, handler: EventHandler<T>): this;
interface IYoungAdultEvent {
giftCard: string,
value: number
}
engine.run(facts)
// Works!
engine.on<IYoungAdultEvent>('young-adult-rocky-mnts', ({ giftCard, value }) => {
console.log(`I got an ${giftCard} card with $${value}!`) // I got an amazon card with $50!
})