Skip to content

[defaultProps] - Related to "How to handle default props?" #4 #15

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from Jun 4, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 43 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<IMyComponentProps, {}> {
static defaultProps: Partial<IMyComponentProps> = {
firstProp: "default",
};
}
```

<details>

<summary>Explanation</summary>

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<IMyComponentProps, {}> {
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`!
</details>

## Extracting Prop Types

Expand Down