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
相关产品推荐
相关产品推荐

