TypeScript · Senior · Question 13 of 75
What does infer N extends number do in a conditional type?
type ToNum<S> = S extends `${infer N extends number}` ? N : never;
type X = ToNum<'42'>;- ✓Correct answer: Infers
Nwith a constraint -Xbecomes the literal type42 - 2Converts the string
'42'to a number at runtime viaNumber() - 3Causes a compile error:
inferdoesn't supportextends
Explanation
A constraint on infer (TS 4.7+) not only checks compatibility but also lets you infer a literal numeric type from a string. Previously this required nested conditional types.