ts-pattern 是一个 typescript 库,它提供了称为模式匹配的函数式编程概念。它可以通过多种方式显着提高代码可读性:
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.`; } }
之后(带有 ts 模式):
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(); }
请给我运动