BigInt Literal Types Constrain Sizes

Constrain sizes with bigint literal types, compute block-aligned allocations, and reject unsupported values at compile time with ts-expect-error.

TypescriptData Integrity

Code

typescriptsnippet
20 lines
// 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);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

How it works

Everything happens inside the function allocate.

Repetition is confined to for (const size of sizes) — the rest of the file is straight-line.

What to watch for

  • All symbols in play are built-ins of the language — nothing arrives over the network.

Putting it to use

Entry signature: function allocate(bytes: number, block: BlockSize)

Running the file prints labeled results such as packed hex:, fits 64 bits: — each operation’s effect is visible in the output.

Core lines

return blocks * Number(block);

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 `allocate` at load time.