使用模板文字类型是否可能验证一个数字部分是否大于下一个数字部分?

huangapple go评论74阅读模式
英文:

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

问题

我正在尝试为迁移函数定义Record,它使用迁移的方向作为键:v${number}-v${number}

由于这些都是向上的迁移,它们应该被验证为v${first-number}-v${first-number + 1},并且first-number + 1 不应大于我事先定义的某个值。

这是否可以使用模板文字完成,还是必须在运行时执行?

英文:

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

得分: 1

这个应该可以。你也可以使用更一般的 Next 实现,使用元组,但速度可能会慢一些。

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

英文:

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

type NRange&lt;
    I extends number,
    To extends number,
    R extends number = never
&gt; = I extends To ? R &amp; number
    : NRange&lt;Next&lt;I&gt;, To, R | I&gt;;

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

type Migration&lt;From extends number, To extends number&gt; =
    `v${From}-v${NRange&lt;Next&lt;From&gt;, To&gt;}`


type M = Migration&lt;2,7&gt;

playground

huangapple
  • 本文由 发表于 2023年2月24日 17:34:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75554838.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定