0

Say I want to define an "integer date" type that looks like YYYYMMDD -- e.g., 20220603. If that were a string, I could use template literal types to do that. Is there any way to similarly narrow the type for an integer (number)?

Sasgorilla
  • 2,403
  • 2
  • 29
  • 56
  • 1
    I don't think you can create a standalone type for this. But a no-op function could validate this. Would [this](https://tsplay.dev/Na16oN) be ok for you? – Tobias S. Jun 03 '22 at 13:54
  • 1
    This is not feasible at the moment. Take a look at [this](https://tsplay.dev/WzOv2w) which also needs a function to incentivize TypeScript to infer and validate the given value. This example is not safe; it allows you to pass February 30th, 2022. You could make it safe but you would need to list out all the possible strings from 1970 to 2022... – kelsny Jun 03 '22 at 14:00
  • @hittingonme - that's pretty darn close! I would think there would be some (convoluted) way to combine more conditional types here to eliminate the Feb 30th case, no? Something like `type Day = Month extends '02' ? 28DayMonth : (Month extends '09' | '03' | '06' | '11' ? 30DayMonth : 31DayMonth)`? (Putting aside leap years for the moment ...) Haven't tried to make that work yet. – Sasgorilla Jun 03 '22 at 14:35
  • 1
    Yeah but do you also want to take into account leap years...? Like I said, this is not really feasible at the moment in TypeScript. – kelsny Jun 03 '22 at 15:32
  • It's really not fair to the TS compiler to mistreat it like [this](https://tsplay.dev/NBkAdm) to force it to implement [Thirty Days Hath September](https://en.wikipedia.org/wiki/Thirty_Days_Hath_September) and leap year rules. One could write up an answer for this, but... is that what anyone really wants? – jcalz Jun 04 '22 at 00:49

0 Answers0