且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Typescript 中定义正则表达式匹配的字符串类型?

更新时间:2022-11-30 12:19:08

没有办法定义这样的类型.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

游乐场链接