Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

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]/;

question from:https://stackoverflow.com/questions/51445767/how-to-define-a-regex-matched-string-type-in-typescript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...