Home > front end >  TS/ESlint, preventing Map access with square brackets
TS/ESlint, preventing Map access with square brackets

Time:11-23

Using a Map, in the example below:

const m = new Map<number, string>();
m.set(1, 'one');
console.log(m.get(1)); // correct way to access the value residing at 1
console.log(m[1]); // incorrect - why is this allowed? how do I prevent this kind of usage?

Running the above code block produces the following output:

one
undefined

I'm curious, why is the square bracket access allowed by TS/ESLint? Shouldn't the compiler and/or linter know that a variable m of type Map will not respond to the square bracket accessor? Is there any way to configure TS or ESLint to warn/error for these types of incorrect usages (specifically when utilizing the Map type)?

CodePudding user response:

It is not allowed. If you set up a TypeScript project with the default configuration, you will get a compile time error when trying to access a property via indexed access if the property does not exist.

const m = new Map<number, string>();
console.log(m[1]);
//          ^^^^ Error: Element implicitly has an 'any' type because type 
//               'Map<number, string>' has no index signature

Particularly responsible for this error is the noImplictAny rule which is included in the strict suite of compiler flags. Accessing property 1 of a Map which does not have a numeric index signature would result in a value of type any triggering the error.

Please note that accessing properties with the bracket notation effectively bypasses the usual property access rules. It is allowed to use this notation to access properties that a type might not have. But the result implicitly being of type any is triggering the error.

  • Related