How to allow a string that is a key of a class

87 views Asked by At

I have the following function:

export const sortAlphabetically = <T>(array: T[], property: string) => 
    array.sort((a: T, b: T) => 
    a[property].localeCompare(b[property]));

The property should be a key in T (as string?), no other values should be accepted. I tried with property: [key in t] but this doesn't work. Is there a way to do this?

1

There are 1 answers

1
captain-yossarian from Ukraine On BEST ANSWER

keyof operator should do the trick

Docs

export const sortAlphabetically = <
  T extends Record<string, string>
>(array: T[], property: keyof T) =>
  array.sort((a: T, b: T) => a[property].localeCompare(b[property]));

You need to assure TypeScript that value of property is string. That's why I have used T extends Record<string, string>