Template literal matching support
cyberixae opened this issue · 2 comments
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)
The syntax could also be
P.templateLiteral`${P.select(P.string)}%`
Edit: that would require microsoft/TypeScript#33304
@phaux An interesting idea. I asked Effect developers if they have considered that https://discord.com/channels/795981131316985866/1227645477122609203