gvergnaud / ts-pattern

🎨 The exhaustive Pattern Matching library for TypeScript, with smart type inference.
MIT License
11.65k stars 120 forks source link

Template literal matching support #227

Open cyberixae opened 6 months ago

cyberixae commented 6 months ago

Is your feature request related to a problem? Please describe.

Currently third party libraries are needed for matching template literals or calling functions with template literals arguments. While using third party libraries works, it would be nice if ts-pattern supported template literal matching out of the box. This would also make it possible to have some synergy with other ts-pattern features such as select which would make accessing matched values less of a hassle.

Describe the solution you'd like

import { match, P } from 'ts-pattern'

const parsePercentage = (u: unknown): number | null =>  match(u).with(
  P.templateLiteral(P.select(P.string), '%'), (str) => Number(str)
).otherwise(() => null)

Describe alternatives you've considered

import * as S from '@effect/schema/Schema'
import { match } from 'ts-pattern'

const fromPercentage = (s: `${number}%`): number => Number(s.slice(0, -1))

const parsePercentage = (u: unknown): number | null =>  match(u).when(S.is(
  S.templateLiteral(S.number, S.literal('%')),
), (str) => fromPercentage(str)).otherwise(() => null)
phaux commented 5 months ago

The syntax could also be

P.templateLiteral`${P.select(P.string)}%`

Edit: that would require microsoft/typescript#33304

cyberixae commented 5 months ago

@phaux An interesting idea. I asked Effect developers if they have considered that https://discord.com/channels/795981131316985866/1227645477122609203