← 中文资源

简体中文版本

BigInt 字面量类型约束尺寸

用 bigint 字面量类型约束块大小,计算按块对齐的分配量,并用 ts-expect-error 拦截不支持的值。

阅读英文原文

运行结果

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

8n -> 104
16n -> 112
32n -> 128
packed hex: 10000000000
fits 64 bits: true

实现说明

全部逻辑都在函数 allocate中。 循环只出现在 for (const size of sizes),它的每次迭代处理一个元素。

使用要点

  • 直接运行文件,输出会带上标签,比如 packed hex:、fits 64 bits:——输出的每一行都能指回产生它的那次调用。

常见问题

安装包是准备工作的一部分吗?

不需要。只用内建 API,安装这一步可以省掉。 文件在加载时定义 allocate。

主要签名是 function allocate(bytes: number, block: BlockSize)

核心语句

return blocks * Number(block);

代码示例

// Bigint literal types restrict allocation sizes to declared values.
type BlockSize = 8n | 16n | 32n;

function allocate(bytes: number, block: BlockSize): number {
  const blocks = Math.ceil(bytes / Number(block));
  return blocks * Number(block);
}

const sizes: BlockSize[] = [8n, 16n, 32n];

for (const size of sizes) {
  console.log(size + "n ->", allocate(100, size));
}

// @ts-expect-error only the declared bigint literals are accepted
allocate(100, 24n);

const packed: bigint = 1n << 40n;
console.log("packed hex:", packed.toString(16));
console.log("fits 64 bits:", packed < 1n << 64n);