0

I wrote a simple function in TypeScript that sorts an array of objects based on one of their property. The code looks like:

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;
  }
}

Then, if I have a type Person, with name and lastname properties, I can sort the list of persons with a call like persons.sort(mySortFunction('name', true)) or persons.sort(mySortFunction('lastname', false)).

The function is working, but I'm not really happy with the typing here. Basically, I want to have something like:

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

and indicates to TypeScript that T should extends a type that has a key which matches the value of sortKey...

How can I set a good typing for my function signature?

1 Answer 1

1

You can use 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"'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I knew that the solution was quite simple indeed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.