Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using string index for array avoids type safety?

Tags:

typescript

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
like image 212
Jason S Avatar asked Jun 18 '26 21:06

Jason S


1 Answers

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

Turn it on and it will throw a compile error:

error

like image 138
David Sherret Avatar answered Jun 20 '26 23:06

David Sherret