Skip to content

Commit b6cb57c

Browse files
authored
use "reverse" defaultProp type pattern
as suggested in typescript-cheatsheets/react#103
1 parent 80fbff0 commit b6cb57c

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

README.md

Lines changed: 12 additions & 12 deletions
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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy