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

How to describe a type that's a union of string with a pattern? #1285

Open
ildede opened this issue Nov 6, 2024 · 1 comment
Open

How to describe a type that's a union of string with a pattern? #1285

ildede opened this issue Nov 6, 2024 · 1 comment

Comments

@ildede
Copy link

ildede commented Nov 6, 2024

I currently have a type defined like this:

export type MyType = 'master' | 'companion' | `master-${number}`;

I'm trying to define the same thing with superstruct, but I'm a bit lost as I can't reach the same definition.
Looking into the documentation didn't help me find other possible solutions, so here what I tried so far.

Thanks in advance!

First try (enums)

const MyType: Describe<MyType> = enums(['master', 'companion', `master-${number()}`]);

I get

Type "master" | "companion" | `master-${string}` is not assignable to type MyType
    Type `master-${string}` is not assignable to type MyType

Second try (union and pattern)

const MyType: Describe<MyType> = union([literal('master'), literal('companion'), pattern(string(), /master-\d+/)]);

I get

TS2322: Type Struct<string, null> is not assignable to type Describe<MyType>
    Types of property TYPE are incompatible.
        Type string is not assignable to type MyType

Third try (pattern)

const MyType: Describe<MyType> = pattern(string(), /^master$|^companion$|^master-\d+$/);

I get

TS2322: Type Struct<string, null> is not assignable to type Describe<MyType>
    Types of property TYPE are incompatible.
        Type string is not assignable to type MyType
@yeoffrey
Copy link
Contributor

yeoffrey commented Nov 6, 2024

cc: @arturmuller

To my understanding I don't think that there is a way in Superstruct to handle templated types like this. I also looked through the documentation and old issues to see if there was a discussion around this but couldn't find anything.

In terms of your examples, they all should work for validation but as I understand it you want the type inference off the struct. I don't think that is supported right now.

Thank you for the detailed issue!

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

2 participants