Typescript: how do i get previous number in types?

Created on 23 Jun 2019  ·  3Comments  ·  Source: microsoft/TypeScript

here is a pattern that gets the next number in types domain

type Nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
type Num = Nums[number];
type Next<N extends Num> = Nums[N] extends number ? Nums[N] : never;
type N2 = Next<1>; // 2

is there a way to get a previous number?

Question

Most helpful comment

Shouldn't this be on Stack Overflow?

type Prev<N extends Num> = { [K in Num]: N extends Next<K> ? K : never }[Num];
// Prev<1> is never, just like Next<9> is never. 🤷‍♂️

All 3 comments

Not sure why you'd want this, but isn't it obvious?

type Nums = [-1, 0, 1, 2, 3, 4, 5, 6, 7];
type Num = Nums[number];
type Prev<N extends Num> = Nums[N] extends number ? Nums[N] : never;
type N2 = Prev<1>; // 0

can you use the original sequence?

Shouldn't this be on Stack Overflow?

type Prev<N extends Num> = { [K in Num]: N extends Next<K> ? K : never }[Num];
// Prev<1> is never, just like Next<9> is never. 🤷‍♂️
Was this page helpful?
0 / 5 - 0 ratings

Related issues

Antony-Jones picture Antony-Jones  ·  3Comments

dlaberge picture dlaberge  ·  3Comments

seanzer picture seanzer  ·  3Comments

blendsdk picture blendsdk  ·  3Comments

kyasbal-1994 picture kyasbal-1994  ·  3Comments