Common Operators and Signatures
Type intersection operator (&)
1 | class WithLoading extends React.Component<P & WithLoadingProps> { ... } |
Generic function
1 | const funcComponent = <P extends object>(Component: React.ComponentType<P>): ... => { ... } |
Type cast
A type cast (props as P) is required when passing props forward from TypeScript v3.2 onwards, due to a likely bug in TypeScript.
1 | return loading ? <LoadingSpinner /> : <Component {...props as P} />; |
Examples
Worth to read:
- about HOCs: https://medium.com/@jrwebdev/react-higher-order-component-patterns-in-typescript-42278f7590fb
Higher Order Components
Higher Order Component in JS
1 | const withLoading = Component => |
Higher Order Component in TS
1 | interface WithLoadingProps { |
Function Higher Order Component in TS
1 | const withLoading = <P extends object>( |
Render Prop Component
1 | interface InjectedCounterProps { |
Usage
1 | interface CounterProps extends InjectedCounterProps { |
Wrapping Render Prop as HOC
1 | import { Subtract, Omit } from 'utility-types'; |
Source: https://medium.com/@jrwebdev/react-render-props-in-typescript-b561b00bc67c
React Hooks
Function Components with Hooks in TS example
1 | // import useState next to FunctionComponent |
Details about React Hooks with TypeScript
- Examples how to use with TS: https://fettblog.eu/typescript-react/hooks/
- TS advanced: https://medium.com/@jrwebdev/react-hooks-in-typescript-88fce7001d0d
- super advanced: https://levelup.gitconnected.com/usetypescript-a-complete-guide-to-react-hooks-and-typescript-db1858d1fb9c
1 | const Counter:FunctionComponent<{ initial?: number }> = ({ initial = 0 }) => { |
with useState
1 | // explicitly setting the types |
with useRef
1 | const inputEl = useRef <HTMLInputElement> null; |
with useContext
1 | type Theme = "light" | "dark"; |
with useReducer
1 | interface State { |