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

如何编写支持Alfa[]或Beta[]的TypeScript通用排序函数?

正确实现通用排序函数

问题根源在于两个核心错误:

  • 泛型T未加约束,TypeScript无法确认它包含creation_date属性
  • 参数类型定义错误,未明确指定为数组类型,导致无法执行数组解构和排序操作

修正后的完整代码

import { isNil } from "lodash";

// 通过泛型约束,确保传入的数组元素都具备creation_date属性
export const sort = <T extends { creation_date: string }>(array?: T[] | null): T[] | undefined => {
  if (isNil(array)) return undefined;
  // 解构数组创建副本,避免修改原数组
  return [...array].sort((a, b) => {
    return Date.parse(b.creation_date) - Date.parse(a.creation_date);
  });
};

可选优化:统一基础接口

如果希望Alfa和Beta的类型关系更清晰,可以先定义一个包含共有属性的基础接口,让两个接口继承它:

// 基础接口,提取两个类型的共有属性
interface BaseEntity {
  id: number;
  creation_date: string;
  updation_date: string;
}

export interface Alfa extends BaseEntity {
  name: string;
  propertyOne: string;
  propertyTwo: string;
}

export interface Beta extends BaseEntity {
  propertyThree: string;
  propetryFour: boolean;
}

// 泛型直接约束为BaseEntity,语义更明确
export const sort = <T extends BaseEntity>(array?: T[] | null): T[] | undefined => {
  if (isNil(array)) return undefined;
  return [...array].sort((a, b) => {
    return Date.parse(b.creation_date) - Date.parse(a.creation_date);
  });
};

以上修改后,TypeScript能正确推断类型,不会再抛出“不是数组类型”的错误,同时保证函数可以安全处理Alfa[]和Beta[]两种数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 11:25:18