简体   繁体   English

打字稿高级类型:遵循预定义模式的字符串

[英]Typescript advanced type: string following a predefined pattern

I would like to set a specific type in typescript, that only accepts strings that follow a specific pattern. 我想在打字稿中设置特定的类型,该类型仅接受遵循特定模式的字符串。 For example, to attribute it to a variable which has to be a date in the following format YYYY/MM/DD. 例如,将其归因于一个变量,该变量必须是以下格式的日期YYYY / MM / DD。

Examples: 例子:

  type Date = "YYYY/MM/DD"; // obviously this type is dum and doesn't do the job, but you get the idea
  let date1:Date = "2019/12/31"  // OK
  let date2:Date = "01/12/2000"  // ERROR
  let date3:Date = "someString"  // ERROR
  let date4:Date = "3190/01/31"  // OK
  let date5:Date = 1528917532543 // ERROR
  let date6:Date = "20/12/31"    // ERROR
  let date7:Date = "2018/06/41"  // ERROR !!

Is this possible? 这可能吗?

There is an open issue for regex-validated string types for this kind of scenario (formatted strings, enforced at the type level). 对于这种情况(格式字符串,在类型级别强制执行), 正则表达式验证的字符串类型存在未解决的问题。

However, this wouldn't be enough for what you are suggesting, as it would be difficult to validate date values (eg a day of 41) using regexes. 但是,这还不足以满足您的建议,因为使用正则表达式很难验证日期值(例如,一天为41)。 There is another (closed) issue that would allow the following: 还有另一个(封闭的)问题 ,它可能导致以下问题:

type FormattedDate (s: string) => new Date(s);

and would cause a compiler error if the string couldn't be converted to a Date . 如果无法将字符串转换为Date ,则会导致编译器错误。

But AFAICT it's not currently possible. 但是AFAICT目前尚不可能。

也许您可以为每种可能性生成字符串文字类型并将所有这些类型组合在一起?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM