typescript - TypeScript: סוג 'Uint8Array' חסר את התכונות הבאות מהסוג 'number[]':
אני עובד על פרויקט תוסף כרום ויש לי בעיה להמיר Uint8Array למחרוזת כשאני משתמש ב׳TypeScript׳ (ניסיתי את אותו קוד בלי TypeScript ולא מופיעים שגיאות).
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
}
}
}
}
הודעת שגיאה היא..
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)
תשובה #1
הבעיה היא שהפונקציה String.fromCharCode מצפה למערך של מספרים (number[]) כארגומנט, לכן עליך להמיר את ה-Uint8Array שלך למערך של מספרים לפני העברתו.
String.fromCharCode.apply(
null,
[...new Uint8Array(details.requestBody.raw[0].bytes)]
)
