Emmanuel Akinfulubi

TypeScriptBasic

Work with a typed array in TypeScript

8 A typed array, added to and walked

fair

Declare an array that holds one type only. Add items, remove one, loop over it, and derive something from it. Keep the compiler happy the whole way.

Stuck? Three hints, smallest first
  1. 1. Both string[] and Array<string> mean the same thing. The first is the usual spelling.
  2. 2. push adds to the end, filter gives you a new array without changing the original.
  3. 3. Under this course’s settings, reading arr[0] gives string | undefined, so check it or use arr[0]! when you are certain.

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

const plates: string[] = ['LAG-441-XA', 'ABJ-772-KM'];

plates.push('ENU-318-PH');
plates.push('KAN-905-BD');

// Remove one without mutating: filter returns a new array.
const withoutKano = plates.filter((p) => !p.startsWith('KAN'));

// Walk it.
for (const plate of plates) console.log('in the fleet:', plate);

// Derive from it.
const lagosOnly = plates.filter((p) => p.startsWith('LAG'));
const joined = plates.join(', ');
const lengths = plates.map((p) => p.length);

// Index access is 'string | undefined' here, so it must be handled.
const first = plates[0];
const firstSafe = first === undefined ? '(empty)' : first;

console.log('without Kano:', withoutKano.length);
console.log('joined:', joined);
console.log('first:', firstSafe);

test('pushed twice', plates.length, 4);
test('filter did not mutate', plates.length - withoutKano.length, 1);
test('only one Lagos plate', lagosOnly, ['LAG-441-XA']);
test('all plates are the same length', lengths, [10, 10, 10, 10]);
test('first element handled', firstSafe, 'LAG-441-XA');

Output


      

The detail worth noticing is the last one. With noUncheckedIndexedAccess switched on, plates[0] is string | undefined, because TypeScript cannot know the array is not empty. That feels annoying for one line and then saves you from the single most common runtime crash in JavaScript.

Newsletter

New writing, when it lands.

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