TS/ESlint,防止使用方括号访问 Map

are*_*555 5 javascript node.js typescript

Map在下面的示例中使用, :

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?
Run Code Online (Sandbox Code Playgroud)

运行上面的代码块会产生以下输出:

one
undefined
Run Code Online (Sandbox Code Playgroud)

我很好奇,为什么 TS/ESLint 允许方括号访问?难道编译器和/或 linter 不应该知道m类型变量Map不会响应方括号访问器吗?有没有办法配置 TS 或 ESLint 来警告/错误这些类型的不正确用法(特别是在使用该Map类型时)?

Tob*_* S. 3

不允许。如果您使用默认配置设置 TypeScript 项目,则在尝试通过索引访问访问属性时(如果该属性不存在),您将收到编译时错误。

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
Run Code Online (Sandbox Code Playgroud)

造成此错误的主要因素是编译器标志套件noImplictAny中包含的规则。访问没有数字索引签名的属性将导致触发错误的类型值。strict1Mapany

请注意,使用方括号表示法访问属性实际上绕过了通常的属性访问规则。允许使用此表示法来访问类型可能不具有的属性。但结果隐式any触发了错误。