Is it possible with template literal types to validate that one numeric part is bigger than the next?

95 Views Asked by At

I am trying to define Record for migration functions, that use as key the direction of the migration: v${number}-v${number},

Since those are all UP migrations, they should be validated as v${first-number}-v${first-number + 1} and first-number + 1 should not be more than something I defined if possible.

Does this can be done with template literals or do I have to do it at run time?

1

There are 1 best solutions below

2
geoffrey On

This should do. You can also use a more general implementation of Next using tuples but it can get a little slow

type NRange<
    I extends number,
    To extends number,
    R extends number = never
> = I extends To ? R & number
    : NRange<Next<I>, To, R | I>;

type Next<N extends number> = [1,2,3,4,5,6,7,8,9,10,11,12][N];

type Migration<From extends number, To extends number> =
    `v${From}-v${NRange<Next<From>, To>}`


type M = Migration<2,7>

playground