【问题标题】:How to define the type of a function in TypeScript that sorts an array of objects on one property?如何在 TypeScript 中定义对一个属性上的对象数组进行排序的函数的类型?
【发布时间】:2020-10-09 09:42:41
【问题描述】:

我在 TypeScript 中编写了一个简单的函数,它根据对象的一个​​属性对对象数组进行排序。 代码如下:

export const mySortFunction = (sortKey: string, invert: boolean) => {
  return (a: any, b: any) => {
    if (a[sortKey] < b[sortKey]) {
      return invert ? 1 : -1;
    } else if (a[sortKey] > b[sortKey]) {
      return invert ? -1 : 1;
    }
    return 0;
  }
}

然后,如果我有一个Person 类型,具有namelastname 属性,我可以使用persons.sort(mySortFunction('name', true))persons.sort(mySortFunction('lastname', false)) 之类的调用对人员列表进行排序。

该功能正在运行,但我对这里的输入不太满意。 基本上,我想要这样的东西:

export const mySortFunction = <T>(sortKey: string, invert: boolean) => {
  return (a: T, b: T) => {
    ...
  }
}

并向 TypeScript 指示 T 应该扩展一个类型,该类型的键与 sortKey 的值匹配...

如何为我的函数签名设置一个好的类型?

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

    你可以使用keyof:Playground

    export const mySortFunction = <T>(sortKey: keyof T, invert: boolean) => {
        return (a: T, b: T) => {
            if (a[sortKey] < b[sortKey]) {
                return invert ? 1 : -1;
            } else if (a[sortKey] > b[sortKey]) {
                return invert ? -1 : 1;
            }
            return 0;
        };
    };
    
    type Person = {
        name: string;
        lastname: string;
    };
    
    const persons: Person[] = [
        { name: '1', lastname: '1' },
        { name: '2', lastname: '2' },
    ];
    
    persons.sort(mySortFunction('lastname', true)); // OK
    persons.sort(mySortFunction('test', true)); // Argument of type '"test"' is not assignable to parameter of type '"lastname" | "name"'
    

    【讨论】:

    • 谢谢,我知道解决方案确实很简单。
    猜你喜欢
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 2014-06-26
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    相关资源
    最近更新 更多