Issue
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?
Solution
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.
Answered By - slhck
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.