在作为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} />
答案 0 :(得分:0)
如果仅希望a
回调的函数参数onChange
是Props
中的值之一,则无需使用泛型。 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} />
);
};
如果Component
/ Props
本身是通用的,并且从外部组件接收类型参数(在您的示例中不是这种情况),则可以like this。
干杯,希望对您有帮助