Constrained primitive inference
Concept and syntax
A constrained template infer can recover a primitive literal from a canonical textual spelling. In 5.8.3, "42" yields the literal 42; a numeric spelling that cannot round-trip such as "4.0" can fall back to number. This is type computation, not a parser for user input.
Working example
Save each snippet separately as main.ts in a fresh directory with TypeScript 5.8.3. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts and run accepted snippets with node main.js. Type aliases are erased; assignments and diagnostic checks demonstrate the type relations, not the printed output alone.
type Num<S>=S extends `${infer N extends number}`?N:never;const a:Num<"42">=42; const b:Num<"4.0">=9; console.log(a,b);Expected output:
42 9Common mistake
Intentionally invalid; compile separately and do not execute.
type Num<S>=S extends `${infer N extends number}`?N:never;const a:Num<"42">=43;Expected diagnostic: TS2322. Canonical 42 is a literal type, not unrestricted number.
Practice and recap
Try Num<"oops"> and Num<"0">.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Constrained primitive inference — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Constrained primitive inference is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Num<S>=S extends `${infer N extends number}`?N:never;const a:Num<"42">=42; const b:Num<"4.0">=9; console.log(a,b);Which diagnostic and explanation match the rejected example under the lesson settings?
type Num<S>=S extends `${infer N extends number}`?N:never;const a:Num<"42">=43;What does Num<"4.0"> select in the pinned compiler?