reactjs - 从其中一个 Prop 中选择一个类型

标签 reactjs typescript

我有一个列表组件

type Option = {
  id: string;
};

type Props<O> = {
  options?: O[];
  option?: JSXElementConstructor<O>;
};

const List = <O extends Option>(props: Props<O>) => ...

还有一些像这样的选项组件

type Props = {
  label: string;
  icon?: ElementType;
  onClick?: () => void;
};

const BasicOption = (props: Props) => ...

为了获得正确的类型,我必须这样做

const Example = () => {
  const options = [
    { id: 'a', label: 'Label A', icon: PlaceholderIcon },
    { id: 'b', label: 'Label B', icon: PlaceholderIcon },
    { id: 'c', label: 'Label C', icon: PlaceholderIcon },
    { id: 'd', label: 'Label D', disabled: true },
    { id: 'e', label: 'Label E' },
  ];

  return (
    <List<typeof options[number]>
      options={options}
      option={BasicOption}
    />
  );
};

有没有一种方法可以直接从数组中获得正确的输入以避免 <typeof options[number]>部分?

工作示例:https://codesandbox.io/s/vigorous-hopper-i41uj?file=/src/App.tsx

最佳答案

您需要推断 options 属性并将其与 option 绑定(bind)。

import React, { JSXElementConstructor, ElementType } from "react";


export type BasicProps = {
  label: string;
  icon?: ElementType;
  onClick?: () => void;
};

export const BasicOption = ({ label, icon: Icon, onClick }: BasicProps) => (
  <div onClick={() => onClick?.()}>
    {label}
    {Icon && <Icon />}
  </div>
);


export type Option = {
  id: string;
};

export const List = <Opt extends Option, Options extends Opt[]>({
  options,
  option: Option
}: {
  options: [...Options],
  // same as typeof options[number] but Options is infered
  option: JSXElementConstructor<[...Options][number]>;
}) => (
  <div>
    {Option &&
      options &&
      options.map((option) => <Option key={option.id} {...option} />)}
  </div>
);

export default function App() {
  const options = [
    { id: "a", label: "Label A" },
    { id: "b", label: "Label B" },
    { id: "c", label: "Label C" },
    { id: "d", label: "Label D", disabled: true },
    { id: "e", label: "Label E" }
  ];

  return (
    <List options={options} option={BasicOption} />
  );
}

Playground

您可以在 my blog 中找到有关函数参数推断的更多信息

关于reactjs - 从其中一个 Prop 中选择一个类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68813143/

相关文章:

node.js - 如何同步处理 api 请求,每个请求等待几秒钟

css - 使用 Webpack 和 font-face 加载字体

javascript - 同时加载多个图像

typescript - 为什么没有关于通用接口(interface)错误实现的消息

arrays - TypeScript 中的数组定义

javascript - React Prop 对象数据未定义

reactjs - axios.post请求获取404

angular - MatCheckbox preventDefault() 和 event.checked 值

javascript - 输入 onChange w/React & TypeScript 错误 : jsx no-lambda no-bind

javascript - 如何停止这个 React useEffect 中的无限循环?