Emmanuel Akinfulubi

TypeScriptAdvanced types

Accept a string or string array in TypeScript

8 Text, or an array of text

fair

Write a function taking either a single piece of text or an array of text. For a single value return its length; for an array return the total length of all its items.

Stuck? Three hints, smallest first
  1. 1. Array.isArray(value) is the guard that separates the two cases.
  2. 2. For the array case, reduce adds up the lengths in one pass.
  3. 3. A neat trick: normalise first with const items = Array.isArray(v) ? v : [v], then you have one code path.

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 totalLength(value: string | string[]): number {
  if (Array.isArray(value)) {
    return value.reduce((n, s) => n + s.length, 0);
  }
  return value.length;
}

// The same job with one code path instead of two, by normalising the input.
function totalLengthTidy(value: string | string[]): number {
  const items = Array.isArray(value) ? value : [value];
  return items.reduce((n, s) => n + s.length, 0);
}

console.log(totalLength('Lagos'));
console.log(totalLength(['Lagos', 'Abuja', 'Kano']));
console.log(totalLengthTidy('Lagos'), totalLengthTidy(['Lagos', 'Abuja', 'Kano']));

test('single value', totalLength('Lagos'), 5);
test('array of three', totalLength(['Lagos', 'Abuja', 'Kano']), 14);
test('empty array', totalLength([]), 0);
test('tidy version, single', totalLengthTidy('Lagos'), 5);
test('tidy version, array', totalLengthTidy(['Lagos', 'Abuja', 'Kano']), 14);

Output


      

The second version is the one to remember. Accepting "one thing or many things" is common, and turning it into "always many things" on the first line means the rest of the function has a single shape to deal with. Array.isArray narrows properly, so no assertion is needed.

Newsletter

New writing, when it lands.

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