microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
101.33k stars 12.54k forks source link

custom regex as type that accepts only matching strings #60292

Closed antonioconselheiro closed 1 month ago

antonioconselheiro commented 1 month ago

🔍 Search Terms

"regex type", "regular expression type"

✅ Viability Checklist

⭐ Suggestion

Hey people, how are you doing? I would like to suggest use regex as a custom type:

const hexId: /[a-z\d]+/ = 'b9283d50ff2db1d95c08395e73556bc5c147e22125280e78c569603ac6854fe6';

also

type HexString = /[a-z\d]+/;
const hexId: HexString = 'b9283d50ff2db1d95c08395e73556bc5c147e22125280e78c569603ac6854fe6';

I searched through the closed and open issues and didn't find any suggestions exactly like this, but maybe I didn't look hard enough, because it seems like a very obvious suggestion to me.

📃 Motivating Example

This will help me create any custom string type.

💻 Use Cases

  1. What do you want to use this for? After validate a string with a regex, by using the regex as type I will be suure that I no need validate that data again.

  2. What shortcomings exist with current approaches? I found nothing functional that can bring me something like this.

  3. What workarounds are you using in the meantime? I'm using string type and crying.

Josh-Cena commented 1 month ago

https://github.com/microsoft/TypeScript/issues/41160

antonioconselheiro commented 1 month ago

I found this issue, but I was not sure if was exactly that

MartinJohns commented 1 month ago

It is exactly that.

antonioconselheiro commented 1 month ago

closed as duplicated