Skip to content

Commit 5a79f68

Browse files
authored
Merge pull request #15 from Attrash-Islam/master
[defaultProps] - Related to "How to handle default props?" #4
2 parents 04fe13e + d701fad commit 5a79f68

File tree

1 file changed

+43
-2
lines changed

1 file changed

+43
-2
lines changed

README.md

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -192,10 +192,51 @@ class App extends React.Component<{
192192

193193
## Typing DefaultProps
194194

195-
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.
195+
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
196+
we choosed to propose this way of implementing them:
196197

197-
**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).**
198+
```ts
199+
interface IMyComponentProps {
200+
firstProp: string;
201+
secondProp: IPerson[];
202+
}
203+
204+
export class MyComponent extends React.Component<IMyComponentProps, {}> {
205+
static defaultProps: Partial<IMyComponentProps> = {
206+
firstProp: "default",
207+
};
208+
}
209+
```
210+
211+
<details>
212+
213+
<summary>Explanation</summary>
214+
215+
This proposal is using `Partial type` feature in TypeScript, which means that the current interface will fullfill a partial
216+
version on the wrapped interface. In that way we can extend defaultProps without any changes in the types!
198217

218+
The other suggestions was related to create a new interface that will look like this:
219+
220+
```ts
221+
interface IMyComponentProps {
222+
firstProp: string;
223+
secondProp: IPerson[];
224+
}
225+
226+
interface IMyComponentDefaultProps {
227+
firstProp: string;
228+
}
229+
230+
export class MyComponent extends React.Component<IMyComponentProps, {}> {
231+
static defaultProps: IMyComponentDefaultProps = {
232+
firstProp: "default",
233+
};
234+
}
235+
```
236+
237+
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
238+
`IMyComponentDefaultProps`!
239+
</details>
199240

200241
## Extracting Prop Types
201242

0 commit comments

Comments
 (0)