|
13 | 13 | * [Stateless Functional Components](#stateless-functional-components)
|
14 | 14 | * [Stateful Class-based Components](#stateful-class-based-components)
|
15 | 15 | * [Typing DefaultProps](#typing-defaultprops)
|
| 16 | + * [propTypes in TypeScript](#proptypes-in-typescript) |
16 | 17 | * [Extracting Prop Types](#extracting-prop-types)
|
17 | 18 | * [Basic Prop Types Examples](#basic-prop-types-examples)
|
18 | 19 | * [Useful React Type Examples](#useful-react-type-examples)
|
@@ -240,6 +241,31 @@ The problem with this approach that if we need to add another prop in the future
|
240 | 241 |
|
241 | 242 | [Something to add? File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new).
|
242 | 243 |
|
| 244 | + |
| 245 | +## propTypes in TypeScript |
| 246 | + |
| 247 | +Since TypeScript is supporting and embracing Types in compile-time some may think that there's no need for injecting the propTypes |
| 248 | +to do the run-time type checking. While that's true in some cases (like developing an app that is totally being used by TypeScript developers), |
| 249 | +injecting the propType is still recommened and relevant in the libraries that is willing to be used |
| 250 | +by JavaScript developers because they won't gain the benefits of the type-system and will likely break things such as: passing props with |
| 251 | +not suitable types. |
| 252 | + |
| 253 | +```ts |
| 254 | +interface IMyComponentProps { |
| 255 | + autoHeight: boolean; |
| 256 | + secondProp: number; |
| 257 | +} |
| 258 | + |
| 259 | +export class MyComponent extends React.Component<IMyComponentProps, {}> { |
| 260 | + static propTypes = { |
| 261 | + autoHeight: PropTypes.bool, |
| 262 | + secondProp: PropTypes.number.isRequired, |
| 263 | + }; |
| 264 | +} |
| 265 | +``` |
| 266 | + |
| 267 | +[Something to add? File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new). |
| 268 | + |
243 | 269 | ## Extracting Prop Types
|
244 | 270 |
|
245 | 271 | Instead of defining prop types *inline*, you can declare them separately (useful for reusability or code organization):
|
|
0 commit comments