← 中文资源

简体中文版本

模板字面量类型约束单位

用模板字面量类型把 CSS 长度限定为「数字加合法后缀」:px、rem、% 之外的写法编译期直接报错,解析前形状已有保证。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

320
1.5

实现说明

模板字面量类型约束单位的核心是函数 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';