Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Updated engine on overload to include generic option #370

Merged

Conversation

jagernet-ops
Copy link

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!
})

types/index.d.ts Outdated Show resolved Hide resolved
chris-pardy added a commit to chris-pardy/json-rules-engine that referenced this pull request Oct 11, 2024
When subscribing to events directly from rules instead of the success and failure events the on method
has the wrong signature for the event handler make it generic to fix it.

Replaces CacheControl#370
Co-Author Michael J. Shalewski <mshalewski@outlook.com>
@chris-pardy chris-pardy merged commit b75acfd into CacheControl:master Oct 15, 2024
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants