bhylu.com

Advertisements

TypeScript Union Types

A union permits one of several types. Before using an operation available on only one member, narrow the value with a check that provides useful evidence.

How it works

Some existing shelf codes are numeric, while newer codes include letters. Rather than convert every value immediately or use any, a union keeps both supported representations visible. A typeof check separates number from string. This is control-flow narrowing: the type available in a branch follows the test that got execution there. Code after the branch must still account for the remaining possibilities.

Run the code

Try in playground loads this source without running it. Choose Run when ready. The existing TypeScript 5.8.3 worker transpiles and executes one file; it does not perform full semantic type checking, load npm imports or provide DOM/Node APIs. Use the local compiler for the type contract.

For a full check, save the three downloads together in a new folder, run npm install, then npm run check. Use npm run build followed by npm start to execute the checked JavaScript with Node. The supplied project enables strict checking, indexed-access checks and exact optional properties.

Example

lesson.ts

function displayCode(code: string | number): string {
  if (typeof code === "number") return "N-" + code.toFixed(0);
  return code.trim().toUpperCase();
}
console.log(displayCode(42));
console.log(displayCode(" b-7 "));

Expected result

N-42
B-7

Only the numeric branch calls toFixed, and only the string branch trims text. The output normalizes both forms for display without pretending they are the same stored value. If fractional codes are not allowed, reject them explicitly rather than let display rounding define identity.