Search code examples
typescriptimplicit-typing

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


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?


Solution

  • 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>