How do template literal types interact with number and bigint literal types embedded inside them?
Short answer
Embedding a `number` or `bigint` type inside a template literal type converts it to its STRING representation in the resulting type (matching how JavaScript's actual template literals coerce numbers to strings at runtime) — embedding a literal number type produces that number's…
Advertisement
AModel answer
Embedding a `number` or `bigint` type inside a template literal type converts it to its STRING representation in the resulting type (matching how JavaScript's actual template literals coerce numbers to strings at runtime) — embedding a literal number type produces that number's specific string form, while embedding the general 'number' type produces a much broader (though still constrained) string pattern.
type Pixels<N extends number> = `${N}px`;
type Width = Pixels<100>; // '100px' -- a specific string literal
type AnyPixelValue = `${number}px`; // matches '0px', '42px', '3.5px', etc. -- any numeric string followed by 'px'Real-world example
Typing CSS-in-JS style dimension values that must be a valid number immediately followed by a unit suffix like 'px' or '%'.
Likely follow-ups
- Does embedding a 'boolean' type inside a template literal type behave similarly, producing 'true' | 'false' as string literals?
Related topics