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

TypeScript中函数泛型参数定义及Map返回类型修正问题

TypeScript函数类型优化方案

1. 泛型的必要性及实现

必须使用泛型,因为sortKeys的属性动态不固定,泛型能让TypeScript根据传入的具体参数自动推断类型,既保留灵活性又保证类型安全,避免object类型过于宽泛导致的类型漏洞。

实现方式:定义泛型T并约束为Record<string, string | undefined>,表示sortKeys是键为字符串、值为string或undefined的对象(undefined对应属性不存在的情况)。代码如下:

export const handleSortableColumns = <T extends Record<string, string | undefined>>(
  headerKeys: string[],
  sortKeys: T
): (string | null)[] => {
  if (!headerKeys) return [];

  // 用??替代||,仅当值为undefined或null时返回null,保留空字符串等有效值
  return headerKeys.map(key => sortKeys[key] ?? null);
};

如果需要更严格的类型约束(确保headerKeys的元素都是sortKeys已有的键),可以把headerKeys的类型改为Array<keyof T>:

export const handleSortableColumns = <T extends Record<string, string | undefined>>(
  headerKeys: Array<keyof T>,
  sortKeys: T
): (string | null)[] => {
  if (!headerKeys) return [];

  return headerKeys.map(key => sortKeys[key] ?? null);
};

2. 正确的返回值类型

原函数返回的数组元素可能是string(当sortKeys存在对应键且值为有效字符串)或null(当键不存在或值为undefined),因此正确的返回类型是(string | null)[],同时去掉了any类型,TypeScript会自动推断map回调的返回类型,无需手动指定。

补充说明

  • 关于||和??的选择:如果业务中空字符串""需要被视为无效值并返回null,可以保留原代码的sortKeys[key] || null;如果空字符串是有效值,建议用??避免误判。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 17:40:28