Skip to content

Instantly share code, notes, and snippets.

@ezheidtmann
Last active October 15, 2024 16:43
Show Gist options
  • Save ezheidtmann/829cd9884713ab4f2e152b22d8519117 to your computer and use it in GitHub Desktop.
Save ezheidtmann/829cd9884713ab4f2e152b22d8519117 to your computer and use it in GitHub Desktop.
Typescript recipe for `defaultProps` in React class components
// 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