Search code examples
typescripttypescript-types

Is there a way to add two numbers together on the type level in typescript?


Suppose I had the following types

type One = 1;
type SmallEvens = 0 | 2 | 4 | 6 | 8 | 10;
type Three = 3;

Is there some kind of type Add<T, U> I could define that adds numbers on the type level like so?

type SmallOdds = Add<One, SmallEvens>; // same as `1 | 3 | 5 | 7 | 9 | 11`
type Four = Add<One, Three> // same as `4`

Alternatively, should I be looking at alternative representations of numbers to achieve this effect? However, being able to convert to something that extends number so that I can use it for tuple indexing would be a big plus.


Solution

  • Update 2022

    I have written a package which handles your issue (and a pretty much all kinds of type level arithmetic), and which completely avoids the "Type instantiation is excessively deep and possibly infinite" limitation.

    https://www.npmjs.com/package/ts-arithmetic

    Here are some examples of what you can do with this package:

    import { Add, Subtract, Multiply, Divide, Pow, Compare, Mod } from 'ts-arithmetic'
    // Check the docs below for more
    
    // Add any two numbers
    type AddExample = Add<1024, 256>
    // 1280
    
    // Subtract any two numbers
    type SubtractExample = Subtract<400, 1000>
    // -600
    
    // Multiply any two numbers
    type MultiplyExample = Multiply<25, 50>
    // 1250
    
    // Divide any two numbers
    type DivideExample = Divide<-1, 800>
    // -0.00125
    
    // Raise a number to an integer power
    type PowExample = Pow<5, 7>
    // 78125
    
    // Compare any two numbers (same rules as JavaScript Array.sort())
    type CompareExample = Compare<123456, 20>
    // 1
    
    // Get the JavaScript mod (i.e. remainder)
    type ModExmaple = Mod<87, 7>
    // 3