Given an interface definition for a property:
interface MyProps {
foo: string,
bar: string
}
And a partial declaring some default props
const defaultProps: Partial<MyProps> {
foo: "baz"
}
Rather than having to merge the properties manually in a functional React component (which doesn't seem to give you any type information)...
const render = (props: MyProps) => {
const safeProps = {...defaultProps, ...props};
}
You can create a generic utility mergeProps
function to do this for you, with a type that can be inferred!
function mergeProps<T>(defaultProps: Partial<T>, props: T): T {
return {...defaultProps, ...props};
}
Which can be called as such:
const render = (props: MyProps) => {
const safeProps = mergeProps(defaultProps, props);
}
In VSCode, IntelliSense will now correctly see safeProps : MyProps