Execute Program

TypeScript Basics: Undefined in Arrays

Welcome to the Undefined in Arrays lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • When we access an element of an array of type string, we expect to get a string in return.

  • >
    let strings: string[] = ['a'];
    let element: string = strings[0];
    element;
    Result:
    'a'Pass Icon
  • There's a case where TypeScript breaks that rule: when accessing indexes that don't exist in the array. In that case, TypeScript will return undefined.

  • >
    let strings: string[] = ['a'];
    let element: string = strings[5];
    element;
    Result:
    undefinedPass Icon
  • >
    const s: string = ['a'][1];
    s;
    Result:
    undefinedPass Icon
  • This seems bad! We now have a value of undefined in a variable of type string. This is almost certainly a bug, and the type system hasn't caught it.

  • TypeScript can't know how long an array will be. Its designers could have made strings[i] have the type string | undefined. That would force us to deal with the undefined that comes out when we access an index beyond the end of the array.

  • However, TypeScript doesn't do that because it would be a burden. We don't want to have to check for undefined every time we do someArray[i].

  • There are two main ways to work around this problem. First, we can check for whether we got an undefined back, even though the TypeScript types don't force us to make that check.

  • >
    const numbers = [1, 2, 3];
    const n = numbers[100];
    const isUndefined = n === undefined ? 'yes' : 'no';
    isUndefined;
    Result:
    'yes'Pass Icon
  • Second, we can use some TypeScript compiler options to prevent this problem entirely. When we enable both of the --noUncheckedIndexedAccess and --strictNullChecks compiler options, the code above causes a type error. However, the finer details of TypeScript's compiler options are out of scope here, and are covered in our more advanced TypeScript courses.