typescriptecmascript-6uint8array

How to properly use fromCharCode.apply with Uint8Array in TypeScript 3?


So I have some code that I inherited that looks like this: String.fromCharCode.apply(null, new Uint8Array(license)); Recently, we had to update the project dependencies and we are not on TypeScript 3 which complains that the code is not correct with this message: Argument of type 'Uint8Array' is not assignable to parameter of type 'number[]'. Type 'Uint8Array' is missing the following properties from type 'number[]': pop, push, concat, shift, and 3 more. I have a few other places with the same errors, and they are all Uint8Array except one that is a Uint16Array. The issue seems to be with some changes to the Uint8Array constructor that has several overloads. I have tried changing the code to const jsonKey: string = String.fromCharCode.apply(null, Array.from(new Uint8Array(license))); and const jsonKey: string = String.fromCharCode.apply(null, Array.prototype.slice.call(new Uint8Array(license))); Neither of these has worked to recreate the original function of the code, but they did suppress the error messages.


Solution

  • You should be able to do something which will be easier to read even if not as compact:

    let jsonKey: string = "";
    (new Uint8Array(license)).forEach(function (byte: number) {
        jsonKey += String.fromCharCode(byte);
    });