Skip to content

Commit a100050

Browse files
committed
use "reverse" defaultProp type pattern
as suggested in typescript-cheatsheets/react#103
1 parent 91183ec commit a100050

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

README.md

+12-12
Original file line numberDiff line numberDiff line change
@@ -432,24 +432,24 @@ const Greet = (props: Props) => {
432432
/*...*/
433433
};
434434
Greet.defaultProps = defaultProps
435+
```
435436

436-
// ////////////////
437-
// class components
438-
// ////////////////
439-
export type Props = {
440-
name: string;
441-
};
437+
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:
442438

443-
export class Greet extends React.Component<Props> {
444-
render() {
445-
const { name } = this.props;
446-
return <div>Hello ${name.toUpperCase()}!</div>;
439+
```tsx
440+
type GreetProps = typeof Greet.defaultProps & {
441+
age: number
442+
}
443+
444+
class Greet extends React.Component<GreetProps> {
445+
static defaultProps = {
446+
name: 'world'
447447
}
448-
static defaultProps: Partial<Props> = { name: 'world' };
448+
/*...*/
449449
}
450450

451451
// Type-checks! No type assertions needed!
452-
let el = <Greet />;
452+
let el = <Greet age={3} />;
453453
```
454454
<details>
455455
<summary>Why does React.FC break defaultProps?</summary>

0 commit comments

Comments
 (0)