Reputation: 6844
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 ...
?
Upvotes: 1
Views: 69
Reputation: 33691
You just need one more level of generic abstraction:
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
Upvotes: 2