Template Literal Types Constrain Units
Constrain CSS length strings to number-plus-unit shapes with template literal types, so invalid units fail compilation before parsing.
Code
// Template literal types constrain strings to real unit shapes:
// a number followed by one allowed suffix
type CssLength = `${number}px` | `${number}rem` | `${number}%`;
function width(rule: CssLength): number {
// The type guarantees the shape, so parseFloat cannot hit garbage
const value = Number.parseFloat(rule);
return Number.isNaN(value) ? 0 : value;
}
const card: CssLength = '320px';
console.log(width(card));
console.log(width('1.5rem'));
// A bare number or a word like 'wide' is rejected at compile time:
// const missingUnit: CssLength = '320';
// const notANumber: CssLength = 'wide';Output
Captured from a sandboxed run of this snippet in the build pipeline.
320
1.5What the template literal type admits
type CssLength = ${number}px|${number}rem|${number}%`` restricts the string to a number followed by one allowed suffix. '320px' and '1.5rem' match a union arm and compile; the commented-out lines — const missingUnit: CssLength = '320' and const notANumber: CssLength = 'wide' — fail compilation before any parsing happens, which is the whole point of putting the shape in the type.
What width receives
width(rule: CssLength) can rely on that shape, so Number.parseFloat(rule) cannot hit garbage; the only remaining branch is Number.isNaN(value) ? 0 : value as a belt-and-braces fallback. The demo prints 320 for the CssLength-annotated card and 1.5 for the inline '1.5rem' — parseFloat stops at the unit boundary and returns just the numeric part.
The line that leans on the guarantee
const value = Number.parseFloat(rule);
With the union type at the boundary, the function never needs to validate the suffix itself — '320em' or 'wide' never reach this line from correctly typed callers.
Interactive Tools for This Topic
FAQ
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. The file defines `width` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.