Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I enforce a key of an object to be of a certain type?

I’m trying to make a function that can take a generic objects key and use that to create a function to sort string properties using String.localCompare but I can’t get TypeScript to understand that a[key] and b[key] are supposed to be strings.

How do I enforce this in TS?

const makeStringSort = <T>(key: keyof T) => {
  return (a: T, b: T) => {
    return a[key].toLowerCase().localeCompare(b[key].toLowerCase());
  };
};
Property 'toLowerCase' does not exist on type 'T[keyof T]'

// example usage

interface Item {
  prop: string;
  other: number;
}
const sortFn = makeStringSort<Item>("prop");
const items: Item[] = [];
items.sort(sortFn);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Updated answer: use mapped types

const makeStringSort = <T extends string>(key: T) => {
  return <
    U extends {
      [Property in T]: string;
    }
  >(
    a: U,
    b: U
  ) => {
    return a[key].toLowerCase().localeCompare(b[key].toLowerCase());
  };
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading