英文:
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>
英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论