Skip to content

TypeScript event typing best practices #1591

Answered by davidkpiano
Cheerazar asked this question in Q&A
Discussion options

You must be logged in to vote

Here's an idea: since any action in actions assume (rightfully) that any event can be sent to it, you have to explicitly guard against unwanted events. One way to do this with TypeScript is to use an assertion function:

function assertEventType<TE extends EventObject, TType extends TE["type"]>(
  event: TE,
  eventType: TType
): asserts event is TE & { type: TType } {
  if (event.type !== eventType) {
    throw new Error(
      `Invalid event: expected "${eventType}", got "${event.type}"`
    );
  }
}

And that way, all you'll need to do is add that function:

        setClaims: assign({
          claims: (_ctx, evt) => {
+           assertEventType(evt, "LOGIN");
            return evt.val…

Replies: 4 comments 10 replies

Comment options

You must be logged in to vote
2 replies
@Cheerazar
Comment options

@Andarist
Comment options

Comment options

You must be logged in to vote
5 replies
@Cheerazar
Comment options

@pke
Comment options

@pke
Comment options

@Andarist
Comment options

@pke
Comment options

Answer selected by Cheerazar
Comment options

You must be logged in to vote
2 replies
@Andarist
Comment options

@karfau
Comment options

Comment options

You must be logged in to vote
1 reply
@Andarist
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
5 participants