【发布时间】:2018-08-29 22:17:25
【问题描述】:
我想通常声明一个函数返回一个解析对象数组的承诺(我认为这将解决 TS 错误;TS 不知道我可以在解析的数组上使用 forEach) .
在openJSON() 函数上(见下文)我尝试过类似的操作:
function OpenJSON(): Promise<Array<{id: string, performance: number, average: number}>> { // ...
但我仍然遇到错误。并且在未来,我希望这个函数能够产生各种不同的对象。有没有一种通用的方法来声明一个对象数组,比如Promise<Array<{}>>?
async function produceDataRows() {
let tableContent = '';
let jsonData = await OpenJSON();
// error occurs here: [ts] Property 'forEach' does not exist on type '{}'.
jsonData.forEach(element => {
// convert this JSON data into table content
});
return tableContent;
};
function OpenJSON() {
return new Promise( (resolve, reject) => {
fs.open(kJsonPath, 'wx', (err, fd) => {
if (err) {
if (err.code === 'EEXIST') {
fs.readFile(kJsonPath, 'utf8', function (err, content) {
if (err) throw err;
resolve(JSON.parse(content));
})
} else {
reject( new Error('When openening performance.JSON, in generateHTML.js, an unexpected error has occured. ' + err) );
}
} else throw Error('There is a problem opening performance.JSON');
})
})
}
【问题讨论】:
-
没有打字稿有一些关键字可以让你指定
any类型吗? -
原来的错误是
[ts] Property 'forEach' does not exist on type '{}'。现在我得到SyntaxError: Unexpected token :类似 Promise> -
它编译得很好in the playground。从外观上看,
Promise<Array<any>>或Promise<any[]>是OpenJSON的正确类型。 -
@jonrsharpe 可以,但
--noImplicitAny不行。无论如何,没有必要使用any,除非你想表达你不知道 JSON 是什么样子的。
标签: javascript arrays typescript promise