2

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


1
  • 1
    Well that would be a terrible thing if they did have it like that. But the good thing is, you can have it like that! Enable the noUncheckedIndexedAccess compiler option and have all the fun in the world asserting things with ! everywhere. Commented Aug 19, 2022 at 23:23

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.