3
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?

3
  • I don't think that's typescript's responsibility Commented Oct 4, 2019 at 8:25
  • Shouldn't it warn that an item at any index could be either a string or undefined? And since that's obviously not the default, what's the best way to manually configure that? Commented Oct 4, 2019 at 8:26
  • 2
    Very relevant issue in Github: micosoft/TypeScript#13778. It's still open and awaiting feedback, and some of the discussion in there involves what people have done to deal with the problem you're facing. Commented Oct 4, 2019 at 18:50

2 Answers 2

3

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 :(

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

4 Comments

But in this case .map(item => item.length) will also warn right? Having to assert there is not desirable.
Hmm yep you're right. I don't know good solution to this issue...
@Gersom TypeScript doesn't do a good job distinguishing "missing" from "present-but-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.
Update: I can't come up with anything remotely reasonable for this other than Array<string | undefined>.
0

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

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

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.