I want to create a functional component in React using Typescript, and I have already set it up according to this Q&A :
export interface CustomProps<T extends object> extends SomeOtherProps<T> {
customProp?: number;
}
const CustomComponent: <T extends object>(props: CustomProps<T>) => JSX.Element = {
customProp = 10,
...props
}) => {
// etc
};
However, this gives me an error in eslint
saying that the props are not validated:
'customProp' is missing in props validation
I can try to add props validation with the generic by adding CustomProps
after the default props:
export interface CustomProps<T extends object> extends SomeOtherProps<T> {
customProp?: number;
}
const CustomComponent: <T extends object>(props: CustomProps<T>) => JSX.Element = {
customProp = 10,
...props
}: CustomProps<any>) => {
// etc
};
But this gives me a warning with "no explicit any
". And if I insert T
, it won't know about it. So how do I address this?
The solution lies in instantiating the type again, just like it was instantiated for the component declaration itself:
export interface CustomProps<T extends object> extends SomeOtherProps<T> {
customProp?: number;
}
const CustomComponent: <T extends object>(props: CustomProps<T>) => JSX.Element = <T extends object>({
customProp = 10,
...props
}: CustomProps<T>) => {
// etc
});
This way, all props will be properly validated.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.