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 -
Replying to @drosenwasser @appsforartists and
Anyway, more discussion on https://github.com/Microsoft/TypeScript/issues/6579 … https://github.com/Microsoft/TypeScript/issues/21037 … https://github.com/Microsoft/TypeScript/issues/21287 …
1 reply 0 retweets 2 likes
Woah awesome! Thank you so much for the links!
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 