(Typescript)如何实例化包含数组类型字段的对象文字?

问题描述 投票:0回答:1

我使用以下代码遇到此错误:

错误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"
    ]
  }

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

感谢您的帮助!

arrays typescript object-literal
1个回答
0
投票

代替new Array<any>(),使用[]。 TypeScript将基于变量的类型定义来推断文字类型。

© www.soinside.com 2019 - 2024. All rights reserved.