Gersom
Gersom

Reputation: 671

Letting typescript warn against accessing first item of possibly empty array

const test: string[] = [];
test[0].length

This code does not throw a TypeScript error. How can you let typescript warn against the fact that a string might actually not exist at a given index?

Upvotes: 3

Views: 1476

Answers (2)

Gersom
Gersom

Reputation: 671

This is now possible using the following option in tsconfig.json:

{
  "compilerOptions": {
    "noUncheckedIndexedAccess": true
  }
}

Upvotes: 0

Richard Haddad
Richard Haddad

Reputation: 1004

You can use this workaround, setting array items as possible undefined:

const test: (string | undefined)[] = [];

test[0].length; // error

if(test[0]) {
  test[0].length; // good
}

I didn't find any eslint rule which can answer to this need :(

Upvotes: 3

Related Questions