3

I'm just learning typescript, and I noticed it doesn't have type safety for arrays when indexing by strings. It works as expected when indexing by number. Anyone explain this? I doubt its a bug but I can't find any information about this behavior. Thanks

let x : string[] = [];
x[0] = 'test'; // OK, as expected
x[0] = 123; // as expected, error TS2322: Type 'number' is not assignable to type 'string'.
x['hi'] = 123; // OK??  Expected error TS2322 as above
0

1 Answer 1

3

It's because you don't have the --noImplicitAny compiler option turned on.

Turn it on and it will throw a compile error:

error

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

2 Comments

That option doesn't seem to cause TS2322 to show up, it seems to be a different check. What would happen if you try x['hi'] = 'bar'? Would it show up the same error as on your screenshot? If so, then it's a generic error/warning related to accessing an array with non-numeric index (~trying to use array as a hash) and completely not about a type mismatch between the array's element type string and assigning 123 -- and from what I understood the OP and TS2322 are about that.
@quetzalcoatl doing x['hi'] = 'bar'; would be the same error. Also, yes, it's an error with --noImplicitAny because the object's type does not have an index signature defined with [key: string]: number;. Arrays have an index signature of [key: number]: T;... in this case T being string.

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.