简体   繁体   中英

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.

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. 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 .

But AFAICT it's not currently possible.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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