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'>;

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.

Further reading

Problem with a question

TypeScript · Senior · question 13

Test yourself

Take the TypeScript · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz