Last active
October 15, 2024 16:43
-
-
Save ezheidtmann/829cd9884713ab4f2e152b22d8519117 to your computer and use it in GitHub Desktop.
Typescript recipe for `defaultProps` in React class components
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Here's a recipe for using `defaultProps` in React class components. It has these attributes: | |
// | |
// - define `defaultProps` once | |
// - parent components can omit optional props | |
// - the type of `this.props` doesn't keep those props optional if they are defined in `defaultProps` | |
import { SetRequired } from "type-fest"; | |
type MyComponentP = { | |
name: string; | |
jobTitle?: string; | |
} | |
class MyComponent extends React.PureComponent<MyComponentP> { | |
static defaultProps = { | |
jobTitle: "Unknown", | |
} | |
// this is the important part -- SetRequired on all the props which we know will be defined | |
props: Readonly<SetRequired<MyComponentP, keyof typeof MyComponent.defaultProps> | |
componentDidUpdate(prevProps: typeof this.props): void { | |
// both `prevProps.jobTitle` and `this.props.jobTitle` are defined | |
} | |
render () { | |
// `this.props.jobTitle` is always defined because it's either | |
// supplied by the parent or has the value from `defaultProps`. | |
} | |
} | |
export const SomeOtherThing = () => { | |
// `jobTitle` is still an optional prop | |
return <MyComponent name="larry" /> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment