Skip to content

Commit

Permalink
use "reverse" defaultProp type pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
zeus-soft-world committed Apr 9, 2019
1 parent e4d19f6 commit 037da3e
Showing 1 changed file with 12 additions and 12 deletions.
24 changes: 12 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -432,24 +432,24 @@ const Greet = (props: Props) => {
/*...*/
};
Greet.defaultProps = defaultProps
```

// ////////////////
// class components
// ////////////////
export type Props = {
name: string;
};
For **Class components**, there are [a couple ways to do it](https://github.com/sw-yx/react-typescript-cheatsheet/pull/103#issuecomment-481061483)(including using the `Pick` utility type) but the recommendation is to "reverse" the props definition:

export class Greet extends React.Component<Props> {
render() {
const { name } = this.props;
return <div>Hello ${name.toUpperCase()}!</div>;
```tsx
type GreetProps = typeof Greet.defaultProps & {
age: number
}

class Greet extends React.Component<GreetProps> {
static defaultProps = {
name: 'world'
}
static defaultProps: Partial<Props> = { name: 'world' };
/*...*/
}

// Type-checks! No type assertions needed!
let el = <Greet />;
let el = <Greet age={3} />;
```
<details>
<summary>Why does React.FC break defaultProps?</summary>
Expand Down

0 comments on commit 037da3e

Please sign in to comment.