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

如何在部分签名不兼容时泛型处理TypedArray?

解决TypeScript中TypedArray.set的类型不兼容问题

问题出在TypeScript对TypedArray的set方法参数做了严格的类型校验:该方法要求参数必须同时满足ArrayLike<number>和ArrayLike<bigint>,但泛型T extends TypedArray无法让TypeScript确定当前具体是哪种TypedArray(比如BigInt64Array的元素是bigint,而其他多数TypedArray元素是number),因此会触发类型不匹配错误。

方案一:通过元素类型映射实现类型安全的调用

我们可以先定义TypedArray与其元素类型的映射关系,再通过类型断言让TypeScript识别参数类型匹配:

type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray 
| Int16Array | Uint16Array
| Int32Array | Uint32Array 
| BigInt64Array | BigUInt64Array
| Float32Array | Float64Array

// 建立TypedArray到其元素类型的映射
type TypedArrayElement<T extends TypedArray> = 
  T extends BigInt64Array | BigUInt64Array ? bigint : number;

function expand<T extends TypedArray>(arr: T, elementCount: number): T {
    const constructor = arr.constructor as new (length: number) => T
    const result = new constructor(arr.length + elementCount)
    // 断言arr为对应元素类型的ArrayLike,消除类型错误
    result.set(arr as ArrayLike<TypedArrayElement<T>>)
    return result
}

方案二:快速绕过类型检查(适合简单场景)

如果不需要严格的类型校验,直接用any断言可以快速解决问题:

type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray 
| Int16Array | Uint16Array
| Int32Array | Uint32Array 
| BigInt64Array | BigUInt64Array
| Float32Array | Float64Array

function expand<T extends TypedArray>(arr: T, elementCount: number): T {
    const constructor = arr.constructor as new (length: number) => T
    const result = new constructor(arr.length + elementCount)
    result.set(arr as any)
    return result
}

方案一保留了类型安全性,推荐在生产代码中使用;方案二更简洁,但会丢失部分类型校验能力。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 03:02:24