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

如何将TypeScript返回数组的箭头函数改造为泛型函数?

改造为泛型函数的解决方案

直接给result函数添加泛型参数,约束传入函数的返回值类型,就能实现你想要的调用方式,同时保留类型安全:

// 带泛型的result函数
const result = <T>(length: number, func: (index: number) => T): T[] => {
  return Array.from({ length }, func);
};

interface MyItemType {
    data1: string,
    data2: string,
    data3: string,
}

export const item = (): MyItemType => {
  return {
    data1: 'data1',
    data2: 'data2',
    data3: 'data3',
  };
};

// 显式指定泛型类型(符合你的需求)
let a = result<MyItemType>(2, item);
// 或者你想要的写法(效果一致)
// let a = <MyItemType[]>result(2, item);

// 自动推断类型(更简洁的写法)
let b = result(3, item); // b的类型会被自动推断为MyItemType[]

关键说明:

  • 泛型参数<T>用来表示数组中元素的类型,让函数可以适配任意类型的返回值。
  • 约束func的类型为(index: number) => T,确保传入的函数返回值与泛型类型匹配,同时兼容Array.from回调函数的参数(回调会接收当前元素的索引)。
  • 返回值定义为T[],TypeScript会明确知道函数返回的是对应类型的数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 13:32:47