【问题标题】:(Typescript) How to instanciate object literal that contain a field of array type?(Typescript)如何实例化包含数组类型字段的对象文字?
【发布时间】:2020-07-08 17:44:30
【问题描述】:

以下代码出现此错误:

错误 TS2693:'any' 仅指一种类型,但在此处用作值

    let modelYaml = this.readFileModel('models/model.yml');

    // Build input model
    let inputModel = {
        elements: any[] = new Array<any>(),  <--Error occured on this line
        relations: any[]= new Array<any>()   <--Error occured on this line
    }
    inputModel.elements.push(modelYaml); <- Error occured

modelYaml 是对象类型(函数 readFileModel 返回任何)

tsconfig.json

 "compilerOptions": {
    "baseUrl": "tsconfig",
    "lib": [
      "es2018",
      "dom"
    ],
    "module": "commonjs",
    "moduleResolution": "node",
    "noEmitOnError": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitAny": true,
    "noImplicitThis": true,
    "noUnusedParameters": true,
    "noUnusedLocals": true,
    "rootDir": "src/",
    "skipDefaultLibCheck": true,
    "skipLibCheck": true,
    "sourceMap": true,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "target": "es6",
    "types": [
      "jasmine",
      "node"
    ]
  }

我很难在 typescript 中找到一个用数​​组描述对象字面量的代码示例。

感谢您的帮助!

【问题讨论】:

  • 你把类型放在错误的地方..let inputModel: { elements: any[], relations: any[] } = { elements: [], relations: [] }typescriptlang.org/docs/handbook/basic-types.html
  • @AlekseyL。谢谢 !问题解决了。您可以回答我的问题,我会将其标记为答案。

标签: arrays typescript object-literal


【解决方案1】:

使用[] 代替new Array&lt;any&gt;()。 TypeScript 将根据变量的类型定义推断文字类型。

【讨论】:

  • 你好迈克尔。如果我只写你所说的,我就会遇到“从不”类型的问题。 @Aleksey L. cmets 解决了问题(其中包含您的想法)。还是谢谢!
  • 太棒了!哦,是的,我忘记了,在任何赋值之前的整个变量定义。
猜你喜欢
  • 1970-01-01
  • 2011-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-05
  • 2021-12-18
  • 1970-01-01
相关资源
最近更新 更多