Search code examples
typescripttypescript-typingscryptojs

Can't add option object to the SHA3 function with typescript


the SHA3 function provides an option to control the output length as shown in this example:

var hash = CryptoJS.SHA3("Message", { outputLength: 512 });
var hash = CryptoJS.SHA3("Message", { outputLength: 384 });
var hash = CryptoJS.SHA3("Message", { outputLength: 256 });
var hash = CryptoJS.SHA3("Message", { outputLength: 224 });

however when used in typescript with @types/crypto-js i am getting the following type error when trying to specify the the outputLength:

Argument of type '{ outputLength: number; }' is not assignable to parameter of type 'string | WordArray | undefined'. Object literal may only specify known properties, and 'outputLength' does not exist in type 'string | WordArray | undefined'.


Solution

  • That's because that function is defined, in @types/crypto-js, as:

    (message: string | LibWordArray, key?: string | WordArray, ...options: any[]) => WordArray;
    

    As you see, it expects three parameters, the second being the key (which is nullable). Just do this:

    CryptoJS.SHA3("Message", undefined, { outputLength: 512});
    

    An it should work.

    By the way, there's another @types for this library, @types\cryptojs, it might suit you better.