【问题标题】:How to get value of an object using typescript in a generic react hook如何在通用反应挂钩中使用打字稿获取对象的值
【发布时间】:2022-11-14 18:49:40
【问题描述】:

我正在创建一个简单的挂钩,通过提供 itemslabelKeyvalueKey 来检索选项对象。

这是我的钩子参数界面:

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

这是钩子本身:

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;

最后这是SelectOption,我打算得到一个这种类型的数组。

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

我是如此接近,但我找不到我在这里失踪的东西。这是我看到的打字稿错误:

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

【问题讨论】:

    标签: reactjs typescript react-hooks


    【解决方案1】:

    现在T 可以有任何形状。您仅将 T 约束为 object 类型。但是您正试图将T 中的值分配给SelectOption 的属性。 SelectOption 的两个属性只接受 stringnumber 作为它们的值来解释错误。

    我们可以限制T 也只有number | string 属性。

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

    Playground

    【讨论】:

    • 在那种情况下,我的 Item 对象的每个属性都将被限制为具有 number | string,但情况不会一直如此,它可能具有嵌套对象或数组等。我错了吗?
    猜你喜欢
    • 2023-02-04
    • 2023-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 2021-11-25
    • 2019-04-19
    相关资源
    最近更新 更多