Last active
November 30, 2020 01:21
-
-
Save karol-majewski/39d7f10c803162d7e9d17106b1947cd7 to your computer and use it in GitHub Desktop.
Type-level addition in TypeScript (2 methods)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Increments { | |
0: 1; | |
1: 2; | |
2: 3; | |
3: 4; | |
4: 5; | |
} | |
interface Decrements { | |
1: 0; | |
2: 1; | |
3: 2; | |
4: 3; | |
5: 4; | |
} | |
type Increment<T extends number> = T extends keyof Increments ? Increments[T] : never; | |
type Decrement<T extends number> = T extends keyof Decrements ? Decrements[T] : never; | |
type Add<T extends number, U extends number> = { | |
finish: U; | |
continue: Add<Decrement<T>, Increment<U>>; | |
}[T extends 0 ? 'finish' : 'continue']; | |
type Five = Add<2, 3>; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A solution without truth tables: