JS Type Checker Wish List: Regex validated strings
type HexColor = /#[0-9a-f]+/i;
const color: HexColor = '#eee'; // fine
const color: HexColor = 'red'; // error!
-
Show this thread
-
I don't really like using regexes here but it's the most intuitive API for defining a validation rule. Super trivial to implement in a type checker too (if it's written in JS, just delegate to the runtime engine). Could have some way to specify the actual message for errors too.
1 reply 0 retweets 10 likesShow this thread -
-
We have it implemented in a branch but apart from the "make sure you pass in only these strings" case which is really compelling, thinking about how you narrow other strings for validation feels off. It means you have to write the same regex in both expression & type positions.
5 replies 0 retweets 13 likes -
Replying to @drosenwasser @appsforartists and
``` function foo(x: /a+-b+/) { /*...*/ } declare var x: string; // Great, we have to write the same regex again. if (x.match(/a+-b+/)) { foo(x); } ```
2 replies 0 retweets 2 likes
``` const regex = /a+-b+/ // Matches is pretty gross, but just some way to turn it into a "validation" type function foo(x: Matches<regex>) { /*...*/ } declare var x: string; if (x.match(regex)) { foo(x); } ```
-
-
Replying to @sebmck @drosenwasser and
How about just using the keyword pattern instead of type, type feels a bit odd and then just use what you suggested.
0 replies 0 retweets 0 likesThanks. Twitter will use this to make your timeline better. UndoUndo
-
Loading seems to be taking a while.
Twitter may be over capacity or experiencing a momentary hiccup. Try again or visit Twitter Status for more information.
he/him 