当我将文件拖放到我的网站上时,我已经提取了一个解析excel函数,我正在使用打字稿,但收到一个奇怪的错误,我无法弄清楚它说类型承诺缺少以下属性{key :数组; exceldoc:数组}
这是调用我的函数的代码
const onDrop = useCallback(async (acceptedFiles) => {
if (acceptedFiles.length > 1) {
creatorStore.addOutputMessages([['error', `More than one file was selected`]]);
return false;
}
const fileNamesplit = acceptedFiles[0].name.split('.');
if (fileNamesplit[1] === 'xls' || fileNamesplit[1] === 'xlsx' || fileNamesplit[1] === 'csv') {
props.setStoreString('');
try {
const parsedExcel = await parseExcelFile(acceptedFiles[0]);
if (parsedExcel.key.length > 0) {
props.onChange('input', false);
setShowDropArea(false);
props.onChange('chips', true);
props.setDropDownKeys(parsedExcel.key);
props.setExcelDocumentObj(parsedExcel.exceldoc);
}
}catch(error) {
creatorStore.addOutputMessages([['error', 'There was an error that occured when trying to read file']]);
dragLeave();
}
}else {
creatorStore.addOutputMessages([['error', 'File type is not supported please upload csv or excel file']]);
return false;
}
return false;
}, [creatorStore, props]);
然后这是我的功能
import * as xlsx from 'xlsx';
export const parseExcelFile = (file: File): {key: Array<string | number>; exceldoc: Array<unknown>} => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
let excelDocumentObject: Array<unknown> = [];
let keys: Array<string | number> = [];
reader.onload = (e) => {
let data = null;
const target = e.target !== null ? e.target : null;
if (target !== null ) {
data = (target as FileReader).result;
}
const workbook = xlsx.read(data, {type: 'binary'});
workbook.SheetNames.map((sheetname,i) => {
try {
const jsonObj = xlsx.utils.sheet_to_json(workbook.Sheets[sheetname]);
if (i > 0) {
excelDocumentObject = excelDocumentObject.concat(jsonObj);
}
else {
excelDocumentObject = jsonObj;
}
keys = keys.concat(Object.keys(jsonObj[0] as string));
} catch(error) {
reject(error);
}
});
resolve({key: keys, exceldoc: excelDocumentObject});
};
reader.readAsBinaryString(file);
});
};
我可以将// @ ts-ignore放在重新调整新的Promise上,并且此代码可以按我期望的那样起作用,但我真的很好奇这个错误在说什么以及如何解决它