泛型键入作为组件支持的函数

时间:2019-09-04 10:28:39

标签: reactjs typescript

在作为Componenet的支柱之一的函数参数中传递通用类型的正确方法是什么。

我尝试过这样的事情:

type Props = {
   children?: JSX.Element;
   onChange?: <T>(a: T, b: number) => void;
}

并像这样使用它(这会产生ts错误):

...
handleChange = (a: SomeType[], b: number) => {
   return 1;
}
...
<Component onChange={this.handleChange} />

1 个答案:

答案 0 :(得分:0)

如果仅希望a回调的函数参数onChangeProps中的值之一,则无需使用泛型。 onChange不返回任何内容,Component用可能的prop值之一调用它。

type Props = {
  children?: JSX.Element;
  myProp: SomeType[];
  onChange?: (
    // exclude here the prop value of children and the callback itself
    // effectively being a: SomeType[]
    a: Props[Exclude<keyof Props, "children" | "onChange">],
    b: number
  ) => void;
};

const Component = (props: Props) => <div>Hello{props.children}</div>;

// declare concrete prop value as example
declare let myProp: SomeType[];

const App = () => {
  const handleChange: Props["onChange"] = (a, b) => {
    return 1;
  };

  return (
    <Component myProp={myProp} onChange={handleChange} />
  );
};

Playground

如果Component / Props本身是通用的,并且从外部组件接收类型参数(在您的示例中不是这种情况),则可以like this

干杯,希望对您有帮助