Our great sponsors
-
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.
Switch statements are extremely limited and suffer from a fall-through hazard that can lead to errors and bad practices. Thankfully, several npm packages can help with type-narrowing discriminated unions, and the ts-pattern library is an excellent choice.
ts-pattern lets you express complex conditions in a single, compact expression akin to pattern matching in functional programming. There is a tc-39 proposal to add pattern matching to the JavaScript language, but it is still in stage 1.
A better way is to analyze the data and create a type-safe schema that can execute against the incoming data at runtime. The excellent package Zod brings runtime semantics to TypeScript without duplicating existing types.
Related posts
- Type-safe event handling in Typescript with zod and ts-match
- From Flaky to Flawless: Angular API Response Management with Zod
- TypeScript Essentials: Distinguishing Types with Branding
- You can’t run away from runtime errors using TypeScript
- Epic Next JS 14 Tutorial Part 4: How To Handle Login And Authentication in Next.js