Alex Long
Alex Long

Reputation: 156

Why doesn't typescript consider destructured array variables as possibly undefined?

In the following code, I would expect the destructured array variables, firstName and lastName, to be of type string | undefined because the array being destructured could have fewer variables than the number being declared, in which case the additional declared variables will be undefined. However, typescript considers them to be type string. Why is that? Thanks

const [firstName, lastName] = fullName.split(' ')

// Typescript produces these types:
// const firstName: string
// const lastName: string


Upvotes: 1

Views: 312

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370759

That's just the way the language was designed. For a similar example, you can do:

const arr = ['foo'];
const val = arr[2];

and val will be typed as a string - despite obviously not existing. This problem extends to everything with index signatures, of which arrays are just one type.

As of TypeScript 4.1, there's an additional config option available, noUncheckedIndexedAccess, that will result in all values taken from an index signature to have a union with undefined. With that on, your original code results in both firstName and lastName being typed as string | undefined. It results in more type-safe code, but can make some things a tiny bit more tedious when you're sure an index exists and always need to assert that it does.

Upvotes: 5

Related Questions