typescriptincrementtypescript-typings

How can I produce an incremented version of a numeric literal type in TypeScript?


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,

Solution

  • This answer is obsolete since recursive conditional types were introduced in TS4.1. And since TS4.8 introduced support for converting string literal types to number literal types. See this answer instead for a solution involving 🤢 base-10 arithmetic on string representations of numbers.


    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.