Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a regex-matched string type in Typescript?

Is it possible to define an interface which has some information on the format of a string? Take the following example:

interface timeMarkers{     markerTime: string[]         }; 

an example would be:

{    markerTime: ["0:00","1:30", "1:48"]                    } 

My question: Is there a way to define the type for markerTime such that that the string value must always match this regex, instead of declaring it as simply string[] and going from there?

var reg = /[0-9]?[0-9]:[0-9][0-9]/;

like image 467
Our_Benefactors Avatar asked Jul 20 '18 15:07

Our_Benefactors


People also ask

How do I match a regular expression in TypeScript?

You should read MDN Reference - RegExp, the RegExp object accepts two parameters pattern and flags which is nullable(can be omitted/undefined). To test your regex you have to use the . test() method, not passing the string you want to test inside the declaration of your RegExp!

What is the type of regex in TypeScript?

TypeScript RegEx is a Regular Expression object for matching text with some pattern. As TypeScript is also a part of JavaScript, similarly regular expressions are also the objects. TypeScript RegEx is the pattern matching standard for replacement and string parsing.

How do you check if a regex matches a string?

Use the test() method to check if a regular expression matches an entire string, e.g. /^hello$/. test(str) . The caret ^ and dollar sign $ match the beginning and end of the string. The test method returns true if the regex matches the entire string, and false otherwise.

What does \\ mean in regex?

\\. matches the literal character . . the first backslash is interpreted as an escape character by the Emacs string reader, which combined with the second backslash, inserts a literal backslash character into the string being read. the regular expression engine receives the string \.


2 Answers

There is no way to define such a type. There is a proposal on GitHub to support this, but it currently does not appear to be a priority. Vote on it and maybe the team might include it in a future release.

Edit

Starting in 4.1 you can define a type that would validate the string without actually defining all the options:

type MarkerTime =`${number| ''}${number}:${number}${number}`  let a: MarkerTime = "0-00" // error let b: MarkerTime = "0:00" // ok let c: MarkerTime = "09:00" // ok  

Playground Link

like image 162
Titian Cernicova-Dragomir Avatar answered Sep 22 '22 03:09

Titian Cernicova-Dragomir


Until regex types become available to the language, you can now use template literal types in TS 4.1.

Let me refer to the question example and illustrate, how to model a time restricted string type called Time. Time expects strings in the format hh:mm (e.g. "23:59") here for simplification.

Step 1: define HH and MM types

Paste following code into your browser web console:
Array.from({length:24},(v,i)=> i).reduce((acc,cur)=> `${acc}${cur === 0 ? "" : "|"}'${String(cur).padStart(2, 0)}'`, "type HH = ") Array.from({length:60},(v,i)=> i).reduce((acc,cur)=> `${acc}${cur === 0 ? "" : "|"}'${String(cur).padStart(2, 0)}'`, "type MM = ") 
Generated result, which we can use as types in TS:
type HH = '00'|'01'|'02'|'03'|'04'|'05'|'06'|'07'|...|'22'|'23' type MM = '00'|'01'|'02'|'03'|'04'|'05'|'06'|'07'|...|'58'|'59' 

Step 2: Declare Time

type Time = `${HH}:${MM}` 

Simple as that.

Step 3: Some testing

const validTimes: Time[] = ["00:00","01:30", "23:59", "16:30"] const invalidTimes: Time[] = ["30:00", "23:60", "0:61"] // all emit error 

Here is a live code example to get play around with Time.

like image 39
bela53 Avatar answered Sep 22 '22 03:09

bela53