简体   繁体   English

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

[英](Typescript) How to instanciate object literal that contain a field of array type?

I have this error with the following code :我有以下代码的错误:

error TS2693: 'any' only refers to a type, but is being used as a value here错误 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 is of type object (function readFileModel return any) 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"
    ]
  }

I had a hard time to find a code sample in typescript that describe object literal with array.我很难在打字稿中找到一个用数​​组描述对象文字的代码示例。

Thanks for your help !谢谢你的帮助 !

Instead of new Array<any>() , use [] .使用[]代替new Array<any>() TypeScript will infer the literal type based upon type definition on the variable. TypeScript 将根据变量的类型定义推断文字类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM