johnnyrocket33
johnnyrocket33

Reputation: 131

TypeScript - Variable implicitly has type 'any' in some locations where its type cannot be determined

I am trying to convert an uploaded file's content to an MD5 hash. I'm trying to declare a global declaration to use inside functions. However, when I try to use it, I get the error Variable 'hasher' implicitly has type 'any' in some locations where its type cannot be determined.

  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;
  }

How can I define that correctly?

Upvotes: 2

Views: 5698

Answers (1)

iamkneel
iamkneel

Reputation: 1498

The problem is that tsc can't determine what hasher is supposed to be. This is one of the rare cases where you have to explicitly define its type, like this:

let hasher: IHasher? = null;

Which tells tsc that hasher is either an IHasher or undefined or null (make sure to import the IHasher type from the hash-wasm package first!)

Upvotes: 5

Related Questions