I'm trying to specify default values for optional props for a React component.
I can do this, and the I can get the value of the optional property 'y' correctly.
interface CompProps {
x: number;
y?: number;
}
const compPropsDefault: CompProps = {
x: 100,
y: 200
}
function CompA({ x, y = compPropsDefault.y }: CompProps = compPropsDefault) {
const props = {x, y};
console.log(props);
}
CompA({ x: 100 })
// Outputs: {"x": 100, "y": 200}
But I need to do { x, y = compPropsDefault.y }
kind of destructuring all the time, which gets cumbersome with larger objects. Also, ideally I'd want to keep all input props in a props
object.
This works, but I couldn't find any docs/examples recommending this. Would it be bad practice to do this instead? Or is there a better way to get the desired result?
function CompB(props: CompProps = compPropsDefault) {
props = { ...props, ...compPropsDefault };
console.log(props);
}