Search code examples
arraystypescriptobject-literal

(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

    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)

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 !


Solution

  • Instead of new Array<any>(), use []. TypeScript will infer the literal type based upon type definition on the variable.