Typescript: increment number type

柔情痞子 提交于 2019-12-31 02:55:17

问题


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. 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,

回答1:


I would just hardcode it like this:

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

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.

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!



来源:https://stackoverflow.com/questions/54243431/typescript-increment-number-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!