You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript报错:Uint8Array无法赋值给number[],如何修复?

修复TypeScript中Uint8Array传递给String.fromCharCode.apply的类型错误

问题场景

使用crypto.subtle.exportKey("spki", cryptoKey)获取到ArrayBuffer后,需要将其转换为字符串以进一步处理为Base64字符串,参照示例编写代码:

const bufferAsString = String.fromCharCode.apply(null, new Uint8Array(buffer));

但TypeScript抛出类型错误:

TS2345: Argument of type 'Uint8Array' is not assignable to parameter of type 'number[]'.

解决方案

方法1:使用Array.from转换为标准数组

将Uint8Array通过Array.from()转换为TypeScript认可的number数组:

const bufferAsString = String.fromCharCode.apply(null, Array.from(new Uint8Array(buffer)));

Array.from()会将类数组结构的Uint8Array转换为标准number数组,完全符合apply方法对第二个参数的类型要求。

方法2:使用展开运算符

展开运算符可以直接提取Uint8Array的元素,既可以直接调用String.fromCharCode,也可以转换为数组后传给apply:

// 直接传递展开后的元素
const bufferAsString = String.fromCharCode(...new Uint8Array(buffer));

// 转为数组后传给apply
const bufferAsString = String.fromCharCode.apply(null, [...new Uint8Array(buffer)]);

这种写法更简洁,同时满足TypeScript的类型校验。

方法3:类型断言(不推荐)

如果需要快速绕过类型检查,可以使用类型断言强制转换类型,但这种方式会跳过TypeScript的类型校验,存在潜在风险:

const bufferAsString = String.fromCharCode.apply(null, new Uint8Array(buffer) as unknown as number[]);

内容的提问来源于stack exchange,提问作者baitendbidz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 16:20:01