tolu / ISO8601-duration

Node/Js-module for parsing and making sense of ISO8601-durations
92 stars 10 forks source link

Better TypeScript typing for ISO8601-duration strings #24

Closed Mesoptier closed 2 years ago

Mesoptier commented 3 years ago

TypeScript has support for constructing string types using template strings (Template Literal Types). Those types could be used to construct a string type that allows only valid ISO8601-duration strings instead of any arbitrary string.

For example, something like this may work:

type Duration =
    | `P${`${number}Y` | ''}${`${number}M` | ''}${`${number}D` | ''}T${`${number}H` | ''}${`${number}M` | ''}${`${number}S` | ''}`
    | `P${number}W`;

// valid assignment
const valid: Duration = 'P1Y2M4DT20H44M12.67S'; 

// invalid assignment: '"test"' is not assignable to type 'Duration'
const invalid: Duration = 'test';

Code example on TS Playground

That being said, I'm not entirely sure if this would actually be useful, since in most use cases the duration strings come from external APIs and so are not typechecked at compilation time. What do you think?

WORMSS commented 2 years ago
const valid: Duration = 'P1Y2M4DT20H44M12,67S';

this is a valid string, but shows as invalid in your typing. image

tolu commented 2 years ago

It's a very cool idea about what can be done with template string types, but... seems like a lot of work to get that beast of a type to work as expected, PR's are very welcome though 😉

WORMSS commented 2 years ago

Not to mention, it doesn't allow P1Y to be a valid type either. Though that would be solved with another union without the T section.