Home > Mobile >  TS strict infer for type number
TS strict infer for type number

Time:01-13

I want to infer the number type in the following function:

type Options = { count: number };

function foo<O extends Options>(options: O): O['count'] extends 3 ? 'x' : 'y' {}

foo({ count: 3 }) // x
foo({ count: 4 }) // y

Is there any way to do it without using as const or count: 1 | 2 | 3 ...?

CodePudding user response:

You just need one more level of generic abstraction:

TS Playground

type Options<N extends number = number> = { count: N };

function foo <N extends number, O extends Options<N>>(options: O): O['count'] {
  return options.count;
}

foo({ count: 3 }) // 3
foo({ count: 4 }) // 4
  •  Tags:  
  • Related