Reputation: 671
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
Reputation: 671
This is now possible using the following option in tsconfig.json
:
{
"compilerOptions": {
"noUncheckedIndexedAccess": true
}
}
Upvotes: 0
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