Search code examples
reactjstypescriptreact-typescript

How to access typescript type keys?


There was a following task and I cannot understand in any way how to make it.

I have TypeScript type. It is an object with enumerated keys. I want to make a universal function for filtering an array, which consists of objects of this type.

In the function below, oldArray is the array of objects to filter, and keyOldArray is one of the keys of type TObject . I know that I need to use this function in two different places and that the two keys that will be used are name and description for example. How do I specify this for TypeScript? Thank you all in advance!

type TObject = {
  id: string;
  description: string;
  name: string;
  tob: string;
};

const arrayFilter = (oldArray: TObject[], keyOldArray: ???) => {
  return oldArray.filter((item) => item.keyOldArray === somethingConst);
};

Solution

  • You can use typescript's keyof operator: https://www.typescriptlang.org/docs/handbook/2/keyof-types.html

    It looks like you are trying to filter based on the index of keyOldArray, so you'll have to pull out index from the filter callback as well.

    const arrayFilter = (oldArray: TObject[], keyOldArray: (keyof TObject)[]) => {
      return oldArray.filter((item, index) => item[keyOldArray[index]] === somethingConst);
    };