0

I am writing an Interface for a record I want to use in TypeScript. I want to store a date there as an ISOString. However an ISOString is more specific than a regular String. I was hoping to reflect that in my records interface.

So far I haven't been able to figure out how. Is there a default type I can use for this in TypeScript? I was thinking maybe it is possible to use a RegExp instead ( I found no examples using a RegExp as type, so I'm not sure that's even possible ) ?

export default interface Invoice {
    readonly id: number;
    date: string; // ???? should be an ISOString
    payment_term: number;
    client_id: number;
}

PS: Using the Date type is not a solution for me. I want to define an ISOString in my record, not a Date object.

Rob Monhemius
  • 4,822
  • 2
  • 17
  • 49
  • 1
    The closest you can get is a template literal type, but unfortunately as far as I know, you can't specify the number of digits in the numeric parts. Here's a rough idea: https://tsplay.dev/Nng8xm – T.J. Crowder Aug 30 '22 at 16:59
  • 1
    Also relevant : https://stackoverflow.com/questions/51445767/how-to-define-a-regex-matched-string-type-in-typescript – apokryfos Aug 30 '22 at 17:02
  • T.J. Crowder's solution: type ISOString = `${number}-${number}-${number}T${number}:${number}:${number}.${number}Z`;. Note: this checks for a full human readable ISOString as closely as ( currently ) possible. – Rob Monhemius Aug 30 '22 at 17:54

0 Answers0