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

TypeScript类型定义问题:实现输入输出关联的类型化数组函数

解决TypeScript输入与Typed Array输出的类型关联问题

你的核心问题是返回类型定义错误:TypedArrays[T]指向的是构造函数本身(比如Int8Array类),但函数实际返回的是构造函数的实例对象(比如Int8Array的实例)。通过InstanceType<T>工具类型提取构造函数对应的实例类型,就能实现输入与输出的类型关联。

修正后的代码:

const typedArrays = {
  int8: Int8Array,
  uint8: Uint8Array,
  int16: Int16Array,
  uint16: Uint16Array,
};

type TypedArrays = typeof typedArrays;

function doSomething<T extends keyof TypedArrays>(input: T): InstanceType<TypedArrays[T]> {
    return new typedArrays[input]([1, 2, 3]) as InstanceType<TypedArrays[T]>;
}

// 验证类型推断
const arr1 = doSomething('int8'); // arr1 类型自动推断为 Int8Array
const arr2 = doSomething('uint16'); // arr2 类型自动推断为 Uint16Array

关键细节:

  • InstanceType<TypedArrays[T]>:TypeScript内置工具类型,专门用于提取构造函数对应的实例类型,精准匹配new操作后的返回值类型。
  • 类型断言as InstanceType<TypedArrays[T]>:由于TypeScript对索引访问的构造函数实例化存在推断限制,手动断言可消除编译报错,同时保证类型准确性。

修改后,调用doSomething时传入不同字符串参数,TypeScript会自动推断出对应的Typed Array实例类型,满足输入输出类型关联的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 05:30:54