最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - How to restrict usage of indexer without square brackets in object literal? - Stack Overflow

programmeradmin4浏览0评论

Anyone know how to achieve this (other than developing ESLint plugin)?

interface MyInterface {
  Prop1: unknown;
  [key: string]: unknown;
}

const dotNotationTest = {} as MyInterface;
dotNotationTest.Prop1 = "ABC";
dotNotationTest.key = "ABC"; // OK, prevented by tsConfig "noPropertyAccessFromIndexSignature": true
dotNotationTest["AnotherKey"] = "ABC";

const objectliteral: MyInterface = {
  Prop1: "ABC",
  key: "ABC", // Not OK. How to get warning similar to dotNotationTest.key
  ["AnotherKey"]: "ABC"
};

I could not find any relevant tsconfig option or rule for ESLint. Rule based on abstract syntax tree (no-restricted-syntax) can't be applied here as key is not different from Prop1 (from parser perspective)

Playground

发布评论

评论列表(0)

  1. 暂无评论