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

TypeScript泛型函数类型定义:如何限定对象属性为字符串类型?

为大小写不敏感对象数组排序函数添加正确TypeScript类型定义

问题场景

你需要实现一个支持大小写不敏感排序的对象数组排序函数,调用方式如下:

myArray.sort((a, b) => sortArr(a, b, 'someKey'))

原始函数逻辑如下,但添加泛型类型时遇到报错:

const sortArr = (
  firstItem,
  secondItem,
  key
) => (firstItem[key].toLowerCase() > secondItem[key].toLowerCase() ? -1 : 1)

尝试用泛型T定义firstItem和secondItem,用K extends keyof T定义key后,TypeScript报错:

Property 'toLowerCase' does not exist on type 'T[K]'.

原因是TypeScript无法确定T[K]一定是字符串类型,因此需要额外约束该属性的类型。

解决方案

在泛型约束中增加T[K] extends string,明确指定对象的K键对应的属性值必须是字符串类型,这样就能安全调用toLowerCase()方法。

完整类型定义代码

const sortArr = <T, K extends keyof T>(
  firstItem: T,
  secondItem: T,
  key: K
): number => {
  // 此处TypeScript已能确定T[K]是字符串类型
  const firstVal = firstItem[key].toLowerCase();
  const secondVal = secondItem[key].toLowerCase();
  return firstVal > secondVal ? -1 : 1;
};

补充优化(可选)

如果需要支持升序/降序切换,同时完善排序的标准返回逻辑(相等时返回0以保留原顺序),可以调整为:

const sortArr = <T, K extends keyof T>(
  firstItem: T,
  secondItem: T,
  key: K,
  isAscending = true
): number => {
  const firstVal = firstItem[key].toLowerCase();
  const secondVal = secondItem[key].toLowerCase();
  if (firstVal > secondVal) return isAscending ? 1 : -1;
  if (firstVal < secondVal) return isAscending ? -1 : 1;
  return 0;
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 19:35:22