【问题标题】:Typescript error TS7017: Element implicitly has an 'any' type打字稿错误 TS7017:元素隐式具有“任何”类型
【发布时间】:2018-06-24 08:10:41
【问题描述】:

我想做:

let server = {}
for(var i = 0; i < 20; i++) {
    server[i] = 'none';
}

但我收到这个烦人的错误,说我的元素隐含地具有“任何”类型,因为类型“{}”没有索引签名。我的代码有效,但我得到了所有这些错误。有没有办法通过传递编译器标志或使元素显式来使用 gulp 禁用它们?

【问题讨论】:

  • 看起来你实际上是在创建一个数组,在这种情况下为什么不使用new Array(20)?或者只定义索引签名{ [index: number]: string }。你可以关闭 noimplicit any 检查,但如果你要使用 TypeScript,你不妨正确使用它。
  • 当我做 index:numer 的事情时,我得到 3 个语法错误和大约 50 个语义错误,代码比我上面的例子长一点
  • @jonrsharpe 那是一个数组吗?您可以完美地将数字插入到对象中
  • 没有minimal reproducible example,这就是我所能提供的。
  • @Andrew 是的,数组基本上只是一个键是数字的对象。但从语义上讲,OP 正在构建的内容似乎更像数组而不是对象,那么为什么不使用类型系统来加强这一点呢?

标签: windows typescript


【解决方案1】:

只需将其声明为类型any。您可能还需要切换一些编译器选项

let server: any = {}
for(var i = 0; i < 20; i++) {
    server[i] = 'none';
}

该文件名为tsconfig.json,它应该位于您的根目录中。 这是我的样子

{
  "compilerOptions": {
    "outDir": "build/dist",
    "module": "esnext",
    "target": "es2018",
    "lib": ["esnext", "dom"],
    "sourceMap": true,
    "allowJs": true,
    "jsx": "react",
    "moduleResolution": "node",
    "rootDir": "src",
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": false, //here
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true
  },
  "exclude": [
    "node_modules",
    "build",
    "scripts",
    "acceptance-tests",
    "webpack",
    "jest",
    "src/setupTests.ts"
  ]
}

【讨论】:

  • 你知道你的打字稿配置文件在哪里吗?
  • 不,甚至不知道 typescript 有一个配置文件
  • 我在 Windows 8 上,所以我没有“根目录”。你知道它在 Windows 上的位置吗?编辑:找到它:)
  • @displaynamemem。我的意思是你的网络应用程序的根目录。
  • @AlekseyL。 so they are;我的错,感谢您指出这一点。奇怪的是他们没有在文档的实际配置页面中提到它......
猜你喜欢
  • 2019-11-11
  • 2019-07-07
  • 2018-11-30
  • 1970-01-01
  • 2021-12-13
  • 2019-11-11
  • 2021-03-29
  • 2021-11-17
相关资源
最近更新 更多