DEV Community

babar ali
babar ali

Posted on

Transform Your Code with ts-pattern

ts-pattern is a TypeScript library that provides a functional programming concept called pattern matching. It can significantly improve code readability in several ways:

  1. Simplifies Conditional Statements ts-pattern replaces complex if-else chains or switch statements with concise and expressive pattern matching.
  2. Reduces Boilerplate Code It eliminates the need for repetitive checks and type guards, making your code more compact.
  3. Improves Error Handling Pattern matching ensures that all possible cases are handled, reducing the likelihood of errors.
  4. Enhances Expressiveness ts-pattern's syntax clearly communicates the intent of your code, making it easier for others to understand.
  5. Supports Advanced Matching It offers features like guards, arrays, objects, and wildcard patterns, making complex logic easier to manage.
  6. Integrates Well with TypeScript ts-pattern leverages TypeScript's type system, providing type safety and auto-completion.
  7. Reduces Cognitive Load By breaking down complex logic into smaller, manageable pieces, ts-pattern reduces mental effort. Example Before (without ts-pattern):
function greet(person: { name: string; age: number } | null | undefined): string {
  if (person === null) {
    return 'Hello, stranger!';
  } else if (person === undefined) {
    throw new Error('Person is undefined');
  } else {
    return `Hello, ${person.name}! You are ${person.age} years old.`;
  }
}
Enter fullscreen mode Exit fullscreen mode

After (with ts-pattern):

import { match } from 'ts-pattern';

function greet(person: { name: string; age: number } | null | undefined): string {
  return match(person)
    .with(null, () => 'Hello, stranger!')
    .with(undefined, () => { throw new Error('Person is undefined'); })
    .with({ name, age }, ({ name, age }) => `Hello, ${name}! You are ${age} years old.`)
    .exhaustive();
}
Enter fullscreen mode Exit fullscreen mode

Please sporting me

Top comments (0)