我正在尝试将上传文件的内容转换为 MD5 哈希值。我正在尝试声明一个全局声明以在函数内部使用。但是,当我尝试使用它时,出现错误变量“hasher”在无法确定其类型的某些位置隐式具有类型“any”。
private async hashContentMD5() {
// Converts content to MD5
const CryptoJS = require('crypto-js');
const hashwasm = require('hash-wasm');
const chunkSize = 64 * 1024 * 1024;
const fileReader = new FileReader();
let hasher = null;
function hashChunk(chunk: any) {
return new Promise<void>((resolve, reject) => {
fileReader.onload = async (e: any) => {
const view = new Uint8Array(e.target.result);
hasher.update(view);
resolve();
};
fileReader.readAsArrayBuffer(chunk);
});
}
// tslint:disable-next-line:no-shadowed-variable
const readFile = async (file: any) => {
if (hasher) {
hasher.init();
} else {
hasher = await hashwasm.createMD5();
}
const chunkNumber = Math.floor(file.size / chunkSize);
for (let i = 0; i <= chunkNumber; i++) {
const chunk = file.slice(
chunkSize * i,
Math.min(chunkSize * (i + 1), file.size)
);
await hashChunk(chunk);
}
// tslint:disable-next-line:no-shadowed-variable
const hash = hasher.digest();
return Promise.resolve(hash);
};
// Converts Content MD5 to Base64
const file = (document.getElementById('fileName')as any).files[0];
const hash = await readFile(file);
const promiseArray = CryptoJS.enc.Utf8.parse(hash);
const content_md5 = CryptoJS.enc.Base64.stringify(promiseArray);
return content_md5;
}
如何正确定义它?
最佳答案
问题是 tsc
无法确定 hasher
应该是什么。这是必须显式定义其类型的罕见情况之一,如下所示:
let hasher: IHasher? = null;
这告诉 tsc
hasher
是 IHasher
或 undefined
或 null
(确保首先从 hash-wasm
包中导入 IHasher
类型!)
关于TypeScript - 变量在某些无法确定其类型的位置隐式具有类型 'any',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69492567/