如何在 TypeScript 3 中正确使用 fromCharCode.apply 和 Uint8Array?
How to properly use fromCharCode.apply with Uint8Array in TypeScript 3?
所以我继承了一些代码,如下所示:
String.fromCharCode.apply(null, new Uint8Array(license));
最近,我们不得不更新项目依赖项,但我们不在 TypeScript 3 上,它抱怨代码不正确并显示此消息:
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.
我还有其他几个地方有同样的错误,除了一个是 Uint16Array 之外,它们都是 Uint8Array。问题似乎是对具有多个重载的 Uint8Array 构造函数进行了一些更改。我尝试将代码更改为
const jsonKey: string = String.fromCharCode.apply(null, Array.from(new Uint8Array(license)));
和
const jsonKey: string = String.fromCharCode.apply(null, Array.prototype.slice.call(new Uint8Array(license)));
这些都无法重新创建代码的原始功能,但它们确实抑制了错误消息。
你应该能够做一些更容易阅读的事情,即使不是那么紧凑:
let jsonKey: string = "";
(new Uint8Array(license)).forEach(function (byte: number) {
jsonKey += String.fromCharCode(byte);
});
您的第一次尝试几乎成功了;您只需要显式指定通用参数:
String.fromCharCode.apply(null, Array.from<number>(new Uint8Array(license)));
所以我继承了一些代码,如下所示:
String.fromCharCode.apply(null, new Uint8Array(license));
最近,我们不得不更新项目依赖项,但我们不在 TypeScript 3 上,它抱怨代码不正确并显示此消息:
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.
我还有其他几个地方有同样的错误,除了一个是 Uint16Array 之外,它们都是 Uint8Array。问题似乎是对具有多个重载的 Uint8Array 构造函数进行了一些更改。我尝试将代码更改为
const jsonKey: string = String.fromCharCode.apply(null, Array.from(new Uint8Array(license)));
和
const jsonKey: string = String.fromCharCode.apply(null, Array.prototype.slice.call(new Uint8Array(license)));
这些都无法重新创建代码的原始功能,但它们确实抑制了错误消息。
你应该能够做一些更容易阅读的事情,即使不是那么紧凑:
let jsonKey: string = "";
(new Uint8Array(license)).forEach(function (byte: number) {
jsonKey += String.fromCharCode(byte);
});
您的第一次尝试几乎成功了;您只需要显式指定通用参数:
String.fromCharCode.apply(null, Array.from<number>(new Uint8Array(license)));