Skip to content

Commit fa88057

Browse files
[defaultProps] - Related to "How to handle default props?" #4
1 parent eac1017 commit fa88057

File tree

1 file changed

+45
-1
lines changed

1 file changed

+45
-1
lines changed

README.md

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,51 @@ This is not yet written. Please PR or [File an issue](https://github.com/sw-yx/r
188188

189189
# Typing DefaultProps
190190

191-
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. 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).
191+
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
192+
we choosed to propose this way of implementing them:
193+
194+
```ts
195+
interface IMyComponentProps {
196+
firstProp: string;
197+
secondProp: IPerson[];
198+
}
199+
200+
export class MyComponent extends React.Component<IMyComponentProps, {}> {
201+
static defaultProps: Partial<IMyComponentProps> = {
202+
firstProp: "default",
203+
};
204+
}
205+
```
206+
207+
<details>
208+
209+
<summary>Explanation</summary>
210+
211+
This proposal is using `Partial type` feature in TypeScript, which means that the current interface will fullfill a partial
212+
version on the wrapped interface. In that way we can extend defaultProps without any changes in the types!
213+
214+
The other suggestions was related to create a new interface that will look like this:
215+
216+
```ts
217+
interface IMyComponentProps {
218+
firstProp: string;
219+
secondProp: IPerson[];
220+
}
221+
222+
interface IMyComponentDefaultProps {
223+
firstProp: string;
224+
}
225+
226+
export class MyComponent extends React.Component<IMyComponentProps, {}> {
227+
static defaultProps: IMyComponentDefaultProps = {
228+
firstProp: "default",
229+
};
230+
}
231+
```
232+
233+
The problem with this approach that if we need to add another prop in the future to the defaultProps map then I should update the
234+
`IMyComponentDefaultProps`!
235+
</details>
192236

193237

194238
# Extracting Prop Types

0 commit comments

Comments
 (0)