How to define a regex-matched string type in Typescript?
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
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
.