Having default props in a React component is a rather common situation. The most popular way to accomplish this is to pass the default values to a defaultProps
property on the function component. However, this property will be deprecated in the future.
Spoiler: due to the sheer amount of code written with it, it never will be deprecated. It’s more likely that a warning will show in the console.
Anyway, in order to keep things clean and guard from this future warning, I came up with a clean pure TypeScript solution to this problem:
interface Props { name: string; surname?: string; age?: number; } const defaultProps = { surname: 'Doe', }; function MyComponent(props0: Props) { const props = {...defaultProps, ...props0}; return <div>{props.surname}</div>; }
The code above provides the correct behavior and proper TypeScript validation. It ended becoming an answer on StackOverflow.
Since the spread order may be a a bit hard to remember, this function does the trick:
export function defProp<P, D>(props: P, defaultProps: D): P & D { return {...defaultProps, ...props}; } function MyComponent(props0: Props) { const props = defProp(props0, defaultProps); // ... }
No comments:
Post a Comment