我想一般性地声明一个函数返回一个解析对象数组的 promise (我认为这将解决 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');
})
})
}
最佳答案
在这种情况下,您需要在构造 Promise 本身时指定结果类型。
function OpenJSON() {
return new Promise<Array<{ id: string, performance: number, average: number }>>(
(resolve, reject) => {
fs.open(kJsonPath, 'wx', (err, fd) => {
if (err) {
if (err.code === 'EEXIST') {
fs.readFile(kJsonPath, 'utf8', (err, content) => {
if (err) {
reject(err);
}
resolve(JSON.parse(content));
})
} else {
reject(Error('When openening performance.JSON'));
}
} else {
reject(Error('There is a problem opening performance.JSON'));
}
});
});
}
请注意,在上面,我修复了几个错误处理问题。
关于javascript - 用于解析对象数组的 promise 的 typescript ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49395419/