← 中文资源

简体中文版本

单位后缀类型解析尺寸字符串

用模板字面量类型把尺寸串限定成「数字 + 单位后缀」:写错单位在编译期就报错而不是等到解析;后缀匹配要从最长开始,否则 MB 会被当成 B。

阅读英文原文

运行结果

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

524288 bytes
1572864 bytes
2147483648 bytes
512 bytes
round trip: 2MB

实现说明

全部逻辑都在函数 parseSize、formatSize中。 失败是响亮的:SyntaxError 在守卫分支上直接中止当前操作,不做降级。

使用要点

  • 守卫 unit === undefined 成立时借助提前的 throw 直接离开。
  • 演示输出是带标签的(round trip:),每个操作都会留下自己的一行标注。

常见问题

前置条件不满足时如何报错?

在真正开工之前就会抛出 SyntaxError(守卫:unit === undefined)——请在调用点处理,或有意向上传播。

运行前要先安装什么?

什么都不用额外装——运行时自带了代码所需的一切。 文件在加载时定义 parseSize、formatSize。

签名一览:function parseSize(input: SizeString)

核心语句

const unit = UNITS.find((candidate) => bytes >= MULTIPLIERS[candidate]) ?? 'B';
const unit = UNITS.find((candidate) => input.endsWith(candidate));
throw new SyntaxError(`unrecognised unit in ${input}`);

代码示例

type Unit = 'B' | 'KB' | 'MB' | 'GB';

// Template literal type: only a number followed by one of the four
// suffixes type-checks, so a typo like '512XB' never reaches the parser.
type SizeString = `${number}${Unit}`;

const MULTIPLIERS: Readonly<Record<Unit, number>> = {
  B: 1,
  KB: 1024,
  MB: 1024 * 1024,
  GB: 1024 * 1024 * 1024,
};

// Longest suffix first: '512MB'.endsWith('B') is also true,
// so 'B' must be tested last or every MB would be read as bytes.
const UNITS: readonly Unit[] = ['GB', 'MB', 'KB', 'B'];

function parseSize(input: SizeString): number {
  const unit = UNITS.find((candidate) => input.endsWith(candidate));
  if (unit === undefined) {
    throw new SyntaxError(`unrecognised unit in ${input}`);
  }
  const amount = Number(input.slice(0, -unit.length));
  if (!Number.isFinite(amount)) {
    throw new SyntaxError(`not a number: ${input}`);
  }
  return amount * MULTIPLIERS[unit];
}

const uploadLimit: SizeString = '512KB';
console.log(parseSize(uploadLimit), 'bytes');
console.log(parseSize('1.5MB'), 'bytes');
console.log(parseSize('2GB'), 'bytes');
console.log(parseSize('512B'), 'bytes');

// These fail compilation — the suffix is checked before parsing:
// const typo: SizeString = '512XB';
// parseSize('512');

// Formatting back has to produce a valid SizeString; the cast marks that seam.
function formatSize(bytes: number): SizeString {
  const unit = UNITS.find((candidate) => bytes >= MULTIPLIERS[candidate]) ?? 'B';
  const amount = Math.round(bytes / MULTIPLIERS[unit]);
  return `${amount}${unit}` as SizeString;
}

console.log('round trip:', formatSize(parseSize('1.5MB')));