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

Angular中如何动态传入字符串属性名对对象数组排序?

解决TypeScript动态对象数组排序的索引类型错误

问题根源

你遇到的TypeScript错误核心原因有两个:

  • sortBy被定义为宽泛的string类型,TypeScript无法确认它是目标对象的合法键;
  • 就算是合法键,也可能对应数字类型(比如age),无法直接调用localeCompare方法。

解决方案步骤

1. 先定义清晰的类型别名(可选但推荐)

把数组元素的类型抽离出来,让代码更易维护:

type SampleItem = {
  name: string;
  age: number;
};

// 原数组定义改为
sampleArr: SampleItem[] = [
  { name: "Michael", age: 21},
  { name: "Adam", age: 35 },
  { name: "Zoe", age: 11 },
];

2. 定义约束字符串属性的工具类型

创建一个类型,只提取对象中值为string类型的键,从根源避免传入数字类型的属性:

type StringKeys<T> = { 
  [K in keyof T]: T[K] extends string ? K : never 
}[keyof T];

3. 修改排序函数的参数类型

将sortBy的类型从string改为StringKeys<SampleItem>,这样TypeScript会自动约束它只能是name(age是数字类型,会被自动排除):

sampleArrSort(sortBy: StringKeys<SampleItem>) {
  this.sampleArr.sort((a, b) => a[sortBy].localeCompare(b[sortBy]));
  console.log(this.sampleArr);
}

效果验证

  • 合法调用:this.sampleArrSort("name"),编译正常,排序逻辑正常执行;
  • 非法调用:this.sampleArrSort("age"),编译阶段直接报错,提前避免运行时错误。

简化版(无需工具类型)

如果不想额外定义工具类型,也可以直接用keyof结合类型守卫,可读性稍弱但更简洁:

sampleArrSort(sortBy: keyof SampleItem) {
  // 先判断属性类型是否为string,确保能调用localeCompare
  if (typeof this.sampleArr[0][sortBy] === 'string') {
    this.sampleArr.sort((a, b) => 
      (a[sortBy] as string).localeCompare(b[sortBy] as string)
    );
  }
  console.log(this.sampleArr);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 01:40:06