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?
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?
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 :(
.map(item => item.length) will also warn right? Having to assert there is not desirable.undefined". So Array<string | undefined> adequately describes "numeric-keyed property might be missing" but also matches "numeric-keyed property might be undefined" as in ["hey", undefined, "you"]. So .map() needs to handle undefined also. If you want a different solution you'd basically have to redefine all the Array type definitions. I might be able to come up with something, but Array<string | undefined> is a pretty good answer.Array<string | undefined>.