Emmanuel Akinfulubi

TypeScriptAdvanced types

Union types: string or number in TypeScript

1 A variable that holds text or a number

easy

Declare a variable that may hold either text or a number. Then write a function that accepts text, a number or a boolean and reports which one it got.

Stuck? Three hints, smallest first
  1. 1. A union is written with a vertical bar: string | number.
  2. 2. Inside the function you cannot use a string method until you have proved it is a string. typeof is the proof.
  3. 3. typeof value already returns the words "string", "number" and "boolean", so you may not need any branching at all.

The answer, and proof it works

const same = (a: unknown, b: unknown): boolean =>
  JSON.stringify(a) === JSON.stringify(b);

function test(name: string, got: unknown, want: unknown): void {
  console.log(
    (same(got, want) ? 'ok   ' : 'FAIL ') + name +
    (same(got, want) ? '' : `  got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
  );
}

let result: string | number = 'forty two';
result = 42;

function whichType(value: string | number | boolean): string {
  // typeof hands back exactly the word we want, so no if-chain is needed.
  return typeof value;
}

// And a version that does branch, because usually you want different work
// per type rather than just the name.
function describe(value: string | number | boolean): string {
  if (typeof value === 'string') return `text of length ${value.length}`;
  if (typeof value === 'number') return `number, doubled is ${value * 2}`;
  return `boolean, flipped is ${!value}`;
}

console.log(whichType('hi'), whichType(7), whichType(true));
console.log(describe('hi'));
console.log(describe(7));
console.log(describe(true));

test('result now holds a number', result, 42);
test('whichType on text', whichType('hi'), 'string');
test('whichType on a number', whichType(7), 'number');
test('whichType on a boolean', whichType(true), 'boolean');
test('describe text', describe('hi'), 'text of length 2');
test('describe number', describe(7), 'number, doubled is 14');
test('describe boolean', describe(true), 'boolean, flipped is false');

Output


      

The union is the easy half. The half that matters is that inside describe you cannot touch value.length until typeof value === 'string' has run. TypeScript follows the same control flow you do, and only lets you use what it has proved.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.