ts-pattern icon indicating copy to clipboard operation
ts-pattern copied to clipboard

Regex Support Without When

Open craigmiller160 opened this issue 3 years ago • 1 comments

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

This is a quality-of-life improvement for developers using this library. There are existing alternatives, but this would be a nice improvement.

Describe the solution you'd like

import { match } from 'ts-pattern';

const regex = /\${.*}/;
const prop = '${abc}';
const value = '1.0.0';

const msg = match(prop)
	.with(regex, () => 'Regex')
	.otherwise(() => 'Value');

In that example, a regex I have created would be used in pattern matching. This example does not work, a regex is not an acceptable pattern when passed to with(). Now this can work using when:

import {match, when } from 'ts-pattern';

const regex = /\${.*}/;
const prop = '${abc}';
const value = '1.0.0';

const msg = match(prop)
	.with(when<string>((_) => regex.test(_)), () => 'Regex')
	.otherwise(() => 'Value');

However, it would be nice if we had the ability to apply a regex test directly.

Rather than accepting the regex as a value to the pattern argument, a simple regex wrapper could be provided. This might be easier to implement in terms of its compatibility with ts-pattern's existing type system.

import {match, when, reg} from 'ts-pattern';

const regex = /\${.*}/;
const prop = '${abc}';
const value = '1.0.0';

const msg = match(prop)
	.with(reg(regex), () => 'Regex')
	.otherwise(() => 'Value');

Anyway, just an idea I have.

Describe alternatives you've considered

I have described alternatives above.

Additional context

Just an idea for an enhancement. Thanks.

craigmiller160 avatar Dec 23 '21 17:12 craigmiller160

Nice suggestion, I'll consider it!

In the meantime you can create this reg function in you own codebase if you need it:

import { match, when } from "ts-pattern";

const reg = (expr: RegExp) =>
  when((str: string): str is never => expr.test(str));

const result = match("Hello")
  .with(reg(/^Hel/), (x) => "Matched")
  .otherwise(() => "Doesn't match");

console.log(result);
// => "Matched"

https://codesandbox.io/s/ts-pattern-regexp-example-r1zfl?file=/src/index.tsx

gvergnaud avatar Dec 24 '21 12:12 gvergnaud

Hello, @gvergnaud. Glad to hear you're interesting about this feature, it's will be nice if we can also match the string pattern which come from regex. I'm also interesting about this and love to contribute about this, please that me known if there's something I can help. Thank you very much.

kayac-chang avatar Apr 10 '23 03:04 kayac-chang

I know the proposed solution is a little different, but I'm going to close this issue since you can now use P.string.regex(/[a-z]/) with TS-Pattern v5+

gvergnaud avatar Jun 17 '23 16:06 gvergnaud