Home > Net >  How to get value of an object using typescript in a generic react hook
How to get value of an object using typescript in a generic react hook

Time:11-14

I am creating a simple hook to retrieve option objects by providing the items, labelKey and valueKey.

This is my interface for the hook parameters:

interface IProps<T> {
  items: T[];
  labelKey: keyof T;
  valueKey: keyof T;
}

And this is the hook itself:

const useOptions = <T extends object>(props: IProps<T>) => {
  const { items, labelKey, valueKey } = props;

  const options = useMemo<SelectOption[]>(() => {
    return items.map((item) => ({
      label: item[labelKey],
      value: item[valueKey],
    }));
  }, [items]);
  return options;
};

export default useOptions;

And finally this is the SelectOption and I am planning to get an array of this type.

export interface SelectOption {
  value: number | string;
  label: number | string;
}

I am so close but I couldn't find what I'm missing here. This is the typscript error that I see:

Type 'T[string]' is not assignable to type 'string | number'.

CodePudding user response:

Right now T could have any shape. You only constrained T to be an object type. But you are trying to assign values inside T to the properties of SelectOption. Both properties of SelectOption only accept string or number as their values which explains the error.

We could constrain T to also only have number | string properties.

const useOptions = <
  T extends Record<string, string | number>
>(props: IProps<T>) => {
   /* ... */
};

Playground

  • Related