I've written a function called withDefaults that takes a React component (a function really) and provides an object with default parameter values. It returns a function that that invokes the original React component (function) and merges the default parameters with the final set of parameters.
How can I make required parameters no longer required when they're provided in the default set?
function withDefaultProps<C extends React.ElementType>(Component: c) {
const ResultComponent = Component as React.FunctionComponent;
return (
(defaultProps: Partial<React.ComponentProps<C>>) => (
(finalProps: React.ComponentProps<C>) => (
<ResultComponent {...defaultProps} {...finalProps}>
{finalProps.children}
</ResultComponent>
)
)
)
}
So for example I have a component that requires a and b as properties.
type MyCompProps = {
a: string,
b: string
};
function MyComp(props: MyCompProps) {
return null; // My react structure here
}
const MyPrefilledComp = withDefaultProps(MyComp)({ a: 'alwaysThisString' });
Here's where the Typescript error shows up. When I try to use MyPrefilledComp it still requires that I provide an a property even though its got a default value. How can I adjust my withDefaulProps method to make it optional, without making ALL the properties optional. I've tried Diff and Omit with keyOf but my Typescript is very beginner level so I may be doing those wrong.
// Typescript error: Property a is required
function MyApp() {
return (
<MyPrefilledComp b="a non default value" />
)
}
I've attempted to simplify it and can easily see where the issue is, I'm just not sure how to fix it. Something like: Omit<OriginalProps, Partial<OriginalProps>> but with that partial being given a dynamic type based on the invocation.
function withDefaults(defaultProps: Partial<OriginalProps>) {
return function wrapper(finalProps: OriginalProps) {
return {
...defaultProps,
...finalProps
};
}
}