Home > other >  Argument of type '{ key: string; }[]' is not assignable to parameter of type 'JSON[]&
Argument of type '{ key: string; }[]' is not assignable to parameter of type 'JSON[]&

Time:06-07

I have a file (.json) with the content:

[
    {
        "key": "string1"
    },
    {
        "key": "string2"
    }
]

As far as I understand this file represents JSON[] type.

Then in my typescript class, I import it by the statement:

import file from "../path/file.json";

and then I want to pass it as an argument to a function which expects an argument of JSON[] type.

I defined a type of the method in index.d.ts like this:

takeJsonFile(file: JSON[]): any

But when I pass the file to a method:

takeJsonfile(file);

I get the error message:

Argument of type '{ key: string; }[]' is not assignable to parameter of type 'JSON[]'.
  Type '{ key: string; }' is missing the following properties from type 'JSON': parse, stringify, [Symbol.toStringTag]ts(2345)

my tsconfig.json includes:

    "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "esModuleInterop": true,
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "lib": [
            "es6",
            "dom"
        ],...

What am I missing here? Is the file I am trying to pass not of JSON[] type? Why? I thought that

{
   "key": "value"
}

represents a JSON type of object and more of it in an array represents JSON[] type of object.

CodePudding user response:

you have to create a custom type

type KeyValue = {
  key: string;
};

or class (I don't know your version)

class KeyValue {
  key: string;

  constructor(key: string) {
    this.key = key;
  }
}

and use

function GetKeyValue(items:KeyValue[]){
  
}

CodePudding user response:

I only changed the first line and it is working well. Here is the code.

src/index.ts

const file = require("../file.json");
export function takeJsonFile(file: JSON[]): any {
  console.log(file[0]);
}
takeJsonFile(file);

file.json

[
  {
    "key": "string1"
  },
  {
    "key": "string2"
  }
]

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "esModuleInterop": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "lib": [
        "es6",
        "dom"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "isolatedModules": true,
    "noEmit": true,
  },
  "include": [
    "./src/"
  ]
}
  • Related