Repository navigation
Open
Labels
Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScriptAn idea for TypeScript
Description
This is a pickup of #6579. With the addition of #40336, a large number of those use cases have been addressed, but possibly some still remain.
Update 2023-04-11: Reviewed use cases and posted a write-up of our current evaluation
Search Terms
regex string types
Suggestion
Open question: For people who had upvoted #6579, what use cases still need addressing?
Note: Please keep discussion on-topic; moderation will be a bit heavier to avoid off-topic tangents
Examples
(please help)
Checklist
My suggestion meets these guidelines:
- [?] This wouldn't be a breaking change in existing TypeScript/JavaScript code
- [?] This wouldn't change the runtime behavior of existing JavaScript code
- [?] This could be implemented without emitting different JS based on the types of the expressions
- [?] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- [?] This feature would agree with the rest of TypeScript's Design Goals.
Reacted by iTob191, Thomas Rupprecht, AnyhowStep, Kenji Imamula, Steven, Joe Calzaretta, Andreas M., Matt Gabor, Aleksey Levenstein, Niels Kersic and 572 more
Reacted by AnyhowStep, Eugen Soloviov, Hadrien TOMA, Nikita Balakirev, Justin D Mathew, Hannes Widrig, Ore Landau, Isabella Skořepová, Jas, Gianthra and 88 more
Reacted by Ekadagami, Denis Tokarev, Niwa Takeru, Ivan, ChapelStudios, Goulven CLEC'H, Gyubong Lee, Kyle a.k.a. TechSquidTV, Dino (한도협), Giorgi Tvalmikhelashvili and 43 more
Reacted by Kipras Melnikovas, Max-Chrtr, Anish Patel, Eugen Soloviov, Hadrien TOMA, Peter Hozák, Hannes Widrig, Isabella Skořepová, Jas, Nick Dugger and 39 more
Metadata
Metadata
Assignees
Labels
Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScriptAn idea for TypeScript
Activity
AnyhowStep commentedon Oct 19, 2020
Use case 1, URL path building libraries,
These are the constraints for
.append(),Use case 2,
Use case 3, safer
RegExpconstructor (and similar functions?),flagsshould only contain the charactersg,i,m,s,u,yyume-chan commentedon Oct 20, 2020
Template string type can only be used in conditional type, so it's really a "type validator", not a "type" itself. It also focuses more on manipulating strings, I think it's a different design goal from Regex-validated types.
It's doable to use conditional types to constrain parameters, for example taken from #6579 (comment)
However I think this parttern has several issues:
bmix commentedon Oct 21, 2020
Would this allow me to define type constraints for String to match the XML specification's Name constructs (short summary) and QNames by expressing them as regular expressions? If so, I am all for it :-)
ksabry commentedon Oct 21, 2020
AnyhowStep It isn't the cleanest, but with conditional types now allowing recursion, it seems we can accomplish these cases with template literal types: playground link
AnyhowStep commentedon Oct 22, 2020
We can have compile-time regular expressions now.
But anything requiring conditional types and a generic type param to check is a non-feature to me.
(Well, non-feature when I'm trying to use TypeScript for work. All personal projects have
--noEmitenabled because real TS programmers execute in compile-time)arcanis commentedon Dec 12, 2020
We have a strongly-typed filesystem library, where the user is expected to manipulate "clean types" like
FilenameorPortablePathversus literal strings (they currently obtain those types by using theasoperator on literals, or calling a validator for user-provided strings):I'm investigating template literals to remove the
assyntax, but I'm not sure we'll be able to use them after all:The overhead sounds overwhelming, and makes it likely that there are side effects that would cause problems down the road - causing further pain if we need to revert. Ideally, the solution we're looking for would leave the code above intact, we'd just declare
PortablePathdifferently.RyanCavanaugh commentedon Dec 14, 2020
Maël Nison (@arcanis) it really sounds like you want nominal types (#202), since even if regex types existed, you'd still want the library consumer to go through the validator functions?
hanneswidrig commentedon Feb 16, 2021
I have a strong use case for Regex-validated string types. AWS Lambda function names have a maximum length of 64 characters. This can be manually checked in a character counter but it's unnecessarily cumbersome given that the function name is usually composed with identifying substrings.
As an example, this function name can be partially composed with the new work done in 4.1/4.2. However there is no way to easily create a compiler error in TypeScript since the below function name will be longer than 64 characters.
This StackOverflow Post I created was asking this very same question.
With the continued rise of TypeScript in back-end related code, statically defined data would be a likely strong use case for validating the string length or the format of the string.
johnbillion commentedon Apr 29, 2021
TypeScript supports literal types, template literal types, and enums. I think a string pattern type is a natural extension that allows for non-finite value restrictions to be expressed.
I'm writing type definitions for an existing codebase. Many arguments and properties accept strings of a specific format:
"2021-04-29T12:34:56""1,2,3,4,5000""image/jpeg"fabiospampinato commentedon May 4, 2021
I'd like to argue against Ryan Cavanaugh (@RyanCavanaugh)'s claim in the first post saying that:
As it stands presently TypeScript can't even work with the following type literal:
Throwing an "Expression produces a union type that is too complex to represent.(2590)" error.
That's the equivalent of the following regex:
/^\d{5}$/Just 5 digits in a row.
Almost all useful regexes are more complicated than that, and TypeScript already gives up with that, hence I'd argue the opposite of that claim is true: a small number of use cases have been addressed and the progress with template literals has been mostly orthogonal really.
sushruth commentedon Jun 1, 2021
I just want to add to the need for this because template literals do not behave the way we think explicitly -
this shows template literals are not unique and one can be a subset of another while that is not the intention of use. Regex would let us have a
$at the end to denote end of string that would help discriminate between the constituent types of this union clearly.88 remaining items
HansBrende commentedon Dec 6, 2024
Nearly every use-case mentioned can already be implemented via built-in string template matching & extraction (see, for example, the "wouter" routing library for how they validate and extract route parameters from paths using this method).
The only problem is that the solution in all of these cases requires something like:
What we really want to be able to do is throw away the
Tparameter after validation, as this would allow us to build data structures that don't care which hex code (for example), only that the hex code is valid.We want to be able to say (for example):
So, if I'm not mistaken, it seems like this issue can mostly be reduced to the introduction of existential types issue. Please upvote that one!
(The length-specific use-cases would probably also do well to upvote this length-specific issue.)
saltman424 commentedon Dec 6, 2024
Hans Brende (@HansBrende) how would you use existential types for the below use case?
HansBrende commentedon Dec 6, 2024
Sander Altman (@saltman424)
(Note:
WordCharimplementation would become a whole lot less verbose if the second issue I mentioned gets accepted, as then we could just do:type WordChar = 'ABC...Zabc...z0123456789_'[number].)hbiede commentedon Dec 6, 2024
A) This doesn’t account for Unicode characters in a concise way
B) This is likely too complex for the type parser, no? I’ve had that issue when trying to write just a hex color type, which is only 9 characters at most, let alone an indefinite string
HansBrende commentedon Dec 6, 2024
HBiede (@hbiede)
True, but the original regexp doesn't either since it did not include the
iandu/vflags.If we wanted
/^\w+$/iuinstead, then we'd need to add 2 extra characters toWordChar:ſandK.Unicode-aware expressions in general would obviously be a bit more complicated, but still potentially doable in many cases, including this one (but in many cases not). That's why I stated existential types would cover most of the use-cases, but not all.
Nope. Try it and see! The compiler can handle something like 10K types in a union (not sure what the exact number is), but this is only 26 + 26 + 10 + 1 = 63 types. Your Hex color type was probably defined differently, something like
${Hex}${Hex}${Hex}${Hex}${Hex}${Hex}. That is a union of 16^6 = 16777216 possibilities--much larger. You must use recursion for these sorts of validations to work (and the typescript compiler implements tail-recursion elimination so it is very efficient).If both of the issues I linked to (existential types and string literal length--again, please upvote) were implemented, then you could implement
HexColorvery simply as follows:varkarrus0 commentedon Dec 13, 2024
This would extremely useful for completely ditching ORMs and just using pure typed-SQL queries. Most devs use ORMs for the type-safety but it introduces a ton of method-chaining overhead then you end writing SQL anyways, just with methods.
RyanCavanaugh commentedon Dec 13, 2024
I'm not clear on how regex is useful for SQL queries; can you clarify?
ljharb commentedon Dec 13, 2024
(One of the primary motivating use cases for tagged template literals was for being able to construct a context-aware DSL, including SQL queries and regular expressions)
shaedrich commentedon Dec 14, 2024
I can see both sides here:
UUIDtype:Large table
Solution
Code
Pros
Cons
using string literals
✅ checked at compile time (in theory, see cons)
✅ type is narrowed down
❌ no real meaning at compile time
Together with the constant string length of #34692 mentioned by Hans Brende (@HansBrende) and built-in types like utility intrinsic string manipulation types (
Uppercase,Lowercase,CapitalizeandUncapitalize), that look like common RegExp operation shortcuts (similar to what has been suggested in #34692 (comment)), which actually are just syntactic sugar for the last example above (which could then be optimized under the hood), this would look so much more clean and would be way less cumbersome to implement:Or, strings become generics (strings without type default to
string<any>) similar to arraysHansBrende commentedon Dec 14, 2024
Sebastian Hädrich (@shaedrich) Note: with existential types and string literal length (please upvote both of these issues), all the compiler problems in your first example go away:
shaedrich commentedon Dec 15, 2024
I forgot to mention that my example is a little oversimplified, since
RyanCavanaugh commentedon Dec 16, 2024
By far the best feature for UUID is #43335
But again, how do you even get a malformed UUID in the first place? You can only ever copy-paste them. If you miss a digit from selecting wrong, you should get a more-or-less immediate exception. Why is this happening to people so often?
HansBrende commentedon Dec 16, 2024
Ryan Cavanaugh (@RyanCavanaugh) to answer your question for my own use-cases, the ability to correctly type a UUID would be helpful mainly to ensure that UUIDs round-trip to the server without accidentally putting some other string identifier (whether that be some human-readable identifier, "code", or stringified serial ID) in the "id" field (which aligns with the whole point of using a typed language in the first place: fail at compile time instead of runtime).
Of course, that problem is easily solved by using opaque symbol tags as well, though it feels kind of hacky, especially when certain "special" uuids are hardcoded and must be cast to fit the opaque type.
A more compelling use-case in my mind is hex codes of a certain length, such as RGB or RGBA codes, especially when you are doing math on them and want to avoid writing extra code for error handling of non-valid inputs (or even worse: trying to support all possible formats to avoid error-handling).
codpro2005 commentedon Aug 17, 2025
While this may seem very niche, I'd hope that composable Regex-validated string types could be supported (similar to how the
RegExpconstructor can be used to dynamically create a pattern and flags from strings) by providing an intrinsic type like the following:would be cool if the inverse also worked:
danfry1 commentedon Sep 27, 2026
For the fixed-length subset of this (e.g. #52243, 20-byte vs 32-byte hex strings), there's a workaround that type-checks today (TS 5.4+, including 7.0), with no brands or generic helper functions at the use site:
Playground
How it works:
"" & {}gets normalized into literal text, but"" & Stringstays a placeholder that only accepts"", so it anchors the end of the string. Without it, the last placeholder would match the rest of the input.${bigint}accepts0x…hex, so the intersection also restricts both types to hex.Limits: per-character classes are limited to what a placeholder can express (e.g. any character, a digit via
${bigint}, no uppercase viaLowercase<string>), plus whole-string patterns via intersection, lengths top out around 999 because of the recursion limit, and "character" means a UTF-16 code unit in 5.x but a code point in 7.x.This isn't a substitute for regex types, but it does cover the "exact length + prefix" cases people keep asking for.