Emmanuel Akinfulubi

TypeScriptAdvanced types

Type guards with typeof in TypeScript

4 A type guard on text or a number

easy

Write a function taking either text or a number. Use a check inside the function to work out which one arrived, and log a message suited to each.

Stuck? Three hints, smallest first
  1. 1. The check is typeof value === 'string'. That is the type guard.
  2. 2. After the check, the compiler knows the type inside that branch and lets you use its methods.
  3. 3. Add an else and note that in it the type is number, with nothing left over.

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)}`)
  );
}

function announce(value: string | number): string {
  if (typeof value === 'string') {
    // In here, value is string. Text methods are allowed.
    return `text: "${value.trim()}" has ${value.length} characters`;
  }
  // No union left. TypeScript knows this is number without being told.
  return `number: ${value.toFixed(2)}`;
}

console.log(announce('  Lagos  '));
console.log(announce(3.14159));

// Proof the narrowing is real and not just convention: a variable typed
// as the union cannot use either method before the check.
function lengthOrDigits(value: string | number): number {
  return typeof value === 'string' ? value.length : String(value).length;
}

test('text branch', announce('  Lagos  '), 'text: "Lagos" has 9 characters');
test('number branch', announce(3.14159), 'number: 3.14');
test('length of text', lengthOrDigits('abcd'), 4);
test('digits of a number', lengthOrDigits(1234), 4);

Output


      

Note the message for the text branch: value.trim() removed the spaces but value.length is still 9, because it measures the original. Small thing, but it is the kind of detail an assertion catches and a glance does not.

Newsletter

New writing, when it lands.

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