Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Template literal matching support #227

Open
cyberixae opened this issue Mar 8, 2024 · 2 comments
Open

Template literal matching support #227

cyberixae opened this issue Mar 8, 2024 · 2 comments
Labels
enhancement New feature or request

Comments

@cyberixae
Copy link

cyberixae commented Mar 8, 2024

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
Copy link

phaux commented Apr 10, 2024

The syntax could also be

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

Edit: that would require microsoft/TypeScript#33304

@cyberixae
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants