打字稿:递增数字类型 [英] Typescript: increment number type

查看:100
本文介绍了打字稿:递增数字类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从数字类型T获得具有值T + 1的数字类型Y.

Is it possible from number type T to get number type Y that has value of T+1.

type one = 1

type Increment<T extends number> = ???

type two = Increment<one> // 2

P.S.目前,我已经对值的增量进行了硬编码,但是问题是硬编码的,因此受到限制:

P.S. Currently, I have hardcoded interface of incremented values, but the problem is hardcoded and hence limited:

export type IncrementMap = {
    0: 1,
    1: 2,
    2: 3,

推荐答案

我只是这样硬编码:

type Increment<N extends number> = [
  1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,
  21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,
  38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54, // as far as you need
  ...number[] // bail out with number
][N]

type Zero = 0
type One = Increment<Zero> // 1
type Two = Increment<One>  // 2

type WhoKnows = Increment<12345>; // number

正如我在其他评论中所说的那样,目前对于这种自然递归类型还没有很好的支持.如果支持,我会喜欢的,但它不存在.在实践中,我发现如果某个东西可以处理长度最大为20左右的元组就足够了,但是您的经验可能会有所不同.

As I said in the other comments, there's currently no great support for this kind of naturally recursive type. I would love it if it were supported, but it's not there. In practice I've found that if something can handle tuples up to length 20 or so it's good enough, but your experience may differ.

无论如何,如果有人在这里提出了一个没有经过硬编码但也可以对任意数字有效且表现良好的解决方案(其中Increment<123456789>的结果将为123456790),我很想看到它.也许将来有一天它将成为语言的一部分.

Anyway, if anyone does come up with a solution here that isn't hardcoded but also works and performs well for arbitrary numbers (where Increment<123456789> will evaluate to 123456790) I'd be interested to see it. Maybe one day in the future it will be part of the language.

希望有所帮助;祝你好运!

Hope that helps; good luck!

这篇关于打字稿:递增数字类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆