Unit Suffix Types Parse Size Strings

Constrain size strings to number-plus-suffix template literal types so a mistyped unit fails compilation before any parsing code runs.

TypescriptData Integrity

Code

typescriptsnippet
47 lines
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')));

Output

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

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

How this snippet works

Unit Suffix Types Parse Size Strings keeps everything in the functions parseSize and formatSize.

A guard precedes the SyntaxError: bad state stops the flow there instead of continuing.

What to watch for

  • The toolchain by itself is enough — dependency resolution never happens.
  • The guard unit === undefined short-circuits the flow with an early throw when its condition holds.

Applying it

Its main signature reads function parseSize(input: SizeString)

Expect labeled output — round trip: — when the file runs.

Statements that matter

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

Interactive Tools for This Topic

FAQ

How are precondition violations signaled?
It throws `SyntaxError` before any real work runs, via the guard `unit === undefined` — handle it at the call site or let it propagate deliberately.
What has to be installed first?
Nothing — the runtime itself provides everything the code touches. The file defines `parseSize`, `formatSize` at load time.