Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better TypeScript typing for ISO8601-duration strings #24

Closed
Mesoptier opened this issue Aug 3, 2021 · 3 comments
Closed

Better TypeScript typing for ISO8601-duration strings #24

Mesoptier opened this issue Aug 3, 2021 · 3 comments

Comments

@Mesoptier
Copy link

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
Copy link

WORMSS commented Apr 13, 2022

const valid: Duration = 'P1Y2M4DT20H44M12,67S';

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

@tolu
Copy link
Owner

tolu commented Apr 13, 2022

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 😉

@tolu tolu closed this as completed Apr 13, 2022
@WORMSS
Copy link

WORMSS commented Apr 13, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants