Type-safe event handling in Typescript with zod and ts-match

This page summarizes the projects mentioned and recommended in the original post on dev.to

Our great sponsors
  • SurveyJS - Open-Source JSON Form Builder to Create Dynamic Forms Right in Your App
  • WorkOS - The modern identity platform for B2B SaaS
  • InfluxDB - Power Real-Time Data Analytics at Scale
  • zod

    TypeScript-first schema validation with static type inference

  • ws.on("message", (data) => { try { const parsed = EventSchema.parse(JSON.parse(data)); // Parse will throw for invalid events // ^ // `--- CreatePost | UpdatePost switch (parsed.type) { case "CreatePost": ws.send(handleCreatePost(parsed)) // ^ // `---- type of parsed is CreatePost in this branch return; case "UpdatePost": ws.send(handleUpdatePost(parsed)) // ^ // `---- type of parsed is UpdatePost in this branch return; } } catch (e) { console.error(e); // Also see https://github.com/colinhacks/zod#error-formatting } })

  • ts-pattern

    🎨 The exhaustive Pattern Matching library for TypeScript, with smart type inference.

  • In many functional languages, we have support for pattern-matching with built in support for exhaustiveness check. Typescript does not have this at the moment but there are userland implementations that emulate pattern matching. One such library is ts-pattern, which I have found to work very well in practice.

  • SurveyJS

    Open-Source JSON Form Builder to Create Dynamic Forms Right in Your App. With SurveyJS form UI libraries, you can build and style forms in a fully-integrated drag & drop form builder, render them in your JS app, and store form submission data in any backend, inc. PHP, ASP.NET Core, and Node.js.

    SurveyJS logo
NOTE: The number of mentions on this list indicates mentions on common posts plus user suggested alternatives. Hence, a higher number means a more popular project.

Suggest a related project

Related posts