Search code examples
typescriptgoogle-chrome-extension

Typscript: Type 'Uint8Array' is missing the following properties from type 'number[]':


I've been working on chrome extension project and have a problem parsing Uint8Array into String when I use 'typescript'(I tested same code without typescript and it occurs no errors).

chrome.webRequest.onBeforeRequest.addListener(
        requestListener,
        { urls: ["<all_urls>"] }, ['requestBody']
);
function requestListener(details: any) {
            let id: number = details.requestId;
            let url: string = details.url;
            let method: string = details.method;
            let body: string = ''
            let headers: Header[] = [];
            if (details.method == "POST") {
                body = decodeURIComponent(String.fromCharCode.apply(null,  new Uint8Array(details.requestBody.raw[0].bytes))); // <-- claims error
            }
          
        }
    }

}

Error message is..

var Uint8Array: Uint8ArrayConstructor
new (elements: Iterable<number>) => Uint8Array (+4 overloads)
A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised.

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.ts(2345)

Solution

  • The issue is that the String.fromCharCode function expects an array of numbers (number[]) as the argument, so you need to convert your Uint8Array into an array of numbers before passing it.

    String.fromCharCode.apply(
      null,
      [...new Uint8Array(details.requestBody.raw[0].bytes)]
    )