0

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?

4
  • 2
    That wouldn't really be a type. Say the string was supplied by the user at runtime. How could the compiler check it? Just create a checker function to verify the format. Commented Jun 13, 2018 at 19:27
  • There is no support for this in Typescript Commented Jun 13, 2018 at 19:27
  • Note that some things that match the pattern aren't actually valid dates. This doesn't make sense for a compiler to check - validate this input at runtime. Commented Jun 13, 2018 at 19:29
  • The only way TypeScript could possibly help with this is if it emitted precondition checks when a variable is assigned that throw "Type errors" at runtime if the check fails. That would be super hacky though. Commented Jun 13, 2018 at 19:38

2 Answers 2

1

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 (e.g. 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.

Sign up to request clarification or add additional context in comments.

Comments

0

Maybe you could generate string literal types for every possibility and union all those together?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.