实现说明
模板字面量类型约束单位的核心是函数 width。
常见问题
安装包是准备工作的一部分吗?
不需要。只用内建 API,安装这一步可以省掉。 文件在加载时定义 width。
入口签名:function width(rule: CssLength)
核心语句
return Number.isNaN(value) ? 0 : value;
代码示例
// 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';