【发布时间】:2021-03-07 02:44:17
【问题描述】:
我有以下接口:
interface ButtonProps {
name: string;
}
interface IconButtonProps {
name: string;
icon: string;
}
我正在尝试为以下组件创建类型:
<MyGenericComponent component={button} name="button">...
<MyGenericComponent component={iconButton} name="icon-button" icon="icon">...
我的想法是我无法键入代表 MyGenericComponentProps 的接口,以便它可以接受 component 道具中的反应组件,只要给它的所有其他道具都是给定组件的那些道具会接受!
类似这样的:
interface MyGenericComponentProps<T> extends T {
component: React.FC<T>;
}
...上面的T 可以是ButtonProps 或IconButtonProps。我知道我不能扩展T,因为它是静态未知的,但是我如何确保给出的其余道具是ButtonProps 或IconButtonProps 的道具?
更新:这是回答后的组件定义:
import React from 'react';
import { ButtonProps, IconButtonProps } from '@material-ui/core';
type MyGenericComponentProps<T> = {
component: React.FC<T>;
} & {
[key in keyof T]: T[key];
};
const MyGenericComponent = <T extends object>({ component, ...props }: MyGenericComponentProps<T>) => {
// ... more code here
const Component = component;
return <Component {...props} />;
};
export default MyGenericComponent;
【问题讨论】:
标签: typescript typescript-typings typescript-generics