superstruct icon indicating copy to clipboard operation
superstruct copied to clipboard

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

Open ildede opened this issue 2 years ago • 3 comments

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

ildede avatar Nov 06 '24 16:11 ildede

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!

yeoffrey avatar Nov 06 '24 17:11 yeoffrey

Exactly, to my knowledge typescript doesnt allow to derive a type from a regex, thus superstruct cant do it either, and will never be able to (automatically).

But of course you can do it manually by specifying the type in addition to the regex. As a minimal example sth. like this:

pattern(string(), /master-\d+/) as unknown as Describe<`master-${number}`>

to make it prettier you can write your own helper to wrap it into a nice utility function, but you will still have to specify the type manually.

Your own helpers usage could look like this:

patternTyped(string(), /master-\d+/, {} as `master-${number})`

mellanslag-de avatar Jun 05 '25 11:06 mellanslag-de

Thanks to both of you! I consider it close

ildede avatar Jun 19 '25 05:06 ildede