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

Is there support for template literal types? #268

Closed
David-van-der-Sluijs opened this issue Jul 3, 2021 · 2 comments · Fixed by #279
Closed

Is there support for template literal types? #268

David-van-der-Sluijs opened this issue Jul 3, 2021 · 2 comments · Fixed by #279

Comments

@David-van-der-Sluijs
Copy link

In Typescript there is a thing called Template Literal Types. So I've made this example type:

type Owner = 'Bob' | 'Jeff';
type Dog = `${Owner}'s dog`;

The resulting union type of Dog now is "Bob's dog" | "Jeff's dog".

Is there a way to create a corresponding runtype for this?

@yuhr
Copy link
Collaborator

yuhr commented Jul 8, 2021

Not an intuitive one, but you can achieve it by using Constraint runtype.

const Owner = Union(Literal('Bob'), Literal('Jeff'))
const Dog = String.withConstraint(
  s =>
    Owner.guard(s.match(/^(?<owner>.+)'s dog$/)?.groups?.owner) ||
    'invalid owner',
)

Dog.check("Bob's dog")
// OK

Dog.check("Alice's dog")
// ValidationError: Failed constraint check for string: invalid owner

I think it's better to add this as a separate runtype if possible (especially for the sake of correspondence to TS's type system), but I'm not sure how we should implement. Maybe we could use tagged template?

@yuhr
Copy link
Collaborator

yuhr commented Jul 16, 2021

Hm, I thought it's concise to be able to write it like this:

import { Union, Literal, Template } from 'runtypes'
const Owner = Union(Literal('Bob'), Literal('Jeff'))
const Dog = Template`${Owner}'s dog`

But then Static<typeof Dog> is not possible currently as TS doesn't populate TemplateStringsArray (the type of first parameter of the tagged template function) as a tuple of string literal types. My ideal behavior is suggested here, but it's not likely to be available at least in the near future.

That said, I confirmed runtime type checking is possible in the above syntax. I'm going to file a PR.

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

Successfully merging a pull request may close this issue.

2 participants