如何将枚举限制为仅其成员

时间:2021-03-05 20:39:18

标签: typescript

export enum BASE_ROUTES {
  MODULES = 'modules',
  RESULTS = 'results',
  ISSUES = 'issues',
  FINISH = 'finish',
  NEWSLETTER = 'newsletter',
  REWARDS = 'rewards'
}

目前(除非我配置错误)我可以访问上述枚举以外的内容。例如,我可以做 BASE_ROUTES.foo。有没有办法生成警告并使其成为受限枚举?

上下文:我正在访问 js 文件中的枚举(在我们支持 tsjs 的重构中间)。

我看到的:code

我的 tsconfig.json

{
  "compilerOptions": {
    "target": "ES2018",
    "module": "ESNext",
    "moduleResolution": "Node",
    "lib": ["ESNext", "ESNext.AsyncIterable", "DOM"],
    "esModuleInterop": true,
    "allowJs": true,
    "sourceMap": true,
    "strict": true,
    "noEmit": true,
    "baseUrl": ".",
    "paths": {
      "~/*": ["./*"],
      "@/*": ["./*"]
    },
    "types": ["@types/node", "@nuxt/types"]
  },
  "exclude": ["node_modules"]
}

1 个答案:

答案 0 :(得分:1)

我想如果您想迁移到 Typescript,最好将所有 { “class”:1 , “type” : 1, “propertyType”:1,“propertyTypeStyle”:1} 文件转换为 .js,因为 Typescript 只是 JS 的超集,有效的 JS 在 TS 中仍然有效。

我在你提到的评论中看到:

<块引用>

显然我不希望我的整个 js 文件被检查,因为那里会 有很多“没有隐含的任何”等噪音

为此,您只需在 .ts 文件中将 noImplicitAny 属性设置为 false。像这样:

tsconfig

稍后当您有时间在文件中键入隐式 anys 时,您可以将其设置为 true。查看 here 了解更多信息。