如何在 Typescript 中定义正则表达式匹配的字符串类型? [英] 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[]
};
一个例子是:
{
markerTime: ["0:00","1:30", "1:48"]
}
我的问题:有没有办法定义 markerTime
的类型,使得字符串值必须始终与此正则表达式匹配,而不是简单地将其声明为 string[]
从那里去?
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]/;
推荐答案
没有办法定义这样的类型.GitHub 上有一个提案来支持这一点,但目前似乎不是优先事项.对其进行投票,也许团队可能会将其包含在未来的版本中.
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.
编辑
从 4.1 开始,您可以定义一种类型来验证字符串,而无需实际定义所有选项:
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
这篇关于如何在 Typescript 中定义正则表达式匹配的字符串类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!