我有一个包含以下内容的文件(.json):
[
{
"key": "string1"
},
{
"key": "string2"
}
]据我所知,该文件表示JSON[]类型。
然后,在我的类型记录类中,我通过语句导入它:
import file from "../path/file.json";然后,我想把它作为参数传递给一个函数,它需要一个JSON[]类型的参数。
我在index.d.ts中定义了一种方法,如下所示:
takeJsonFile(file: JSON[]): any但是,当我将file传递给一个方法时:
takeJsonfile(file);我得到了错误消息:
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)我的tsconfig.json包括:
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"esModuleInterop": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"lib": [
"es6",
"dom"
],...我在这里错过了什么?我试图传递的文件不是JSON[]类型的吗?为什么?我以为
{
"key": "value"
}表示对象的JSON类型,数组中的更多对象表示对象的JSON[]类型。
发布于 2022-06-07 01:52:26
我只换了第一行,效果很好。这是密码。
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/"
]
}https://stackoverflow.com/questions/72523771
复制相似问题