diff --git a/README.md b/README.md index b0417e25..370617e4 100644 --- a/README.md +++ b/README.md @@ -192,10 +192,51 @@ class App extends React.Component<{ ## Typing DefaultProps -It is easy to [type defaults for functional components](https://twitter.com/GeeWengel/status/1000242363376205825), but there is some debate in the community on how to type the `static defaultProps` field for class-based components. +It is easy to type a defaultProps static member of a React component. There's more than one way to do it, but since we want to show the neatest code as possible +we choosed to propose this way of implementing them: -**We have an active discussion on several approaches on how to do this. [Please check out our issue here](https://github.com/sw-yx/react-typescript-cheatsheet/issues/4).** +```ts +interface IMyComponentProps { + firstProp: string; + secondProp: IPerson[]; +} + +export class MyComponent extends React.Component { + static defaultProps: Partial = { + firstProp: "default", + }; +} +``` + +
+ +Explanation + +This proposal is using `Partial type` feature in TypeScript, which means that the current interface will fullfill a partial +version on the wrapped interface. In that way we can extend defaultProps without any changes in the types! +The other suggestions was related to create a new interface that will look like this: + +```ts +interface IMyComponentProps { + firstProp: string; + secondProp: IPerson[]; +} + +interface IMyComponentDefaultProps { + firstProp: string; +} + +export class MyComponent extends React.Component { + static defaultProps: IMyComponentDefaultProps = { + firstProp: "default", + }; +} +``` + +The problem with this approach that if we need to add another prop in the future to the defaultProps map then we should update the +`IMyComponentDefaultProps`! +
## Extracting Prop Types