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'
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:
undefined
>
const s: string = ['a'][1];s;Result:
undefined
This seems bad! We now have a value of
undefinedin a variable of typestring. 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 typestring | undefined. That would force us to deal with theundefinedthat 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
undefinedevery time we dosomeArray[i].There are two main ways to work around this problem. First, we can check for whether we got an
undefinedback, 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'
Second, we can use some TypeScript compiler options to prevent this problem entirely. When we enable both of the
--noUncheckedIndexedAccessand--strictNullCheckscompiler 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.