diff --git a/docs/advanced/patterns_by_usecase.md b/docs/advanced/patterns_by_usecase.md index 38ba0f3..e598d9e 100644 --- a/docs/advanced/patterns_by_usecase.md +++ b/docs/advanced/patterns_by_usecase.md @@ -873,47 +873,21 @@ As you can see from the Omit example above, you can write significant logic in y ## Props: Extracting Prop Types of a Component -There are a lot of places where you want to reuse some slices of props because of prop drilling, -so you can either export the props type as part of the module or extract them (either way works). +Sometimes you want the prop types of a component, but it isn't exported. -The advantage of extracting the prop types is that you won't need to export everything, and a refactor of the source of truth component will propagate to all consuming components. - -```ts -import { ComponentProps, JSXElementConstructor } from "react"; - -// goes one step further and resolves with propTypes and defaultProps properties -type ApparentComponentProps< - C extends keyof JSX.IntrinsicElements | JSXElementConstructor -> = C extends JSXElementConstructor - ? JSX.LibraryManagedAttributes - : ComponentProps; -``` - -You can also use them to strongly type custom event handlers if they're not written at the call sites themselves -(i.e. inlined with the JSX attribute): +A simple solution is to use `React.ComponentProps`: ```tsx -// my-inner-component.tsx -export function MyInnerComponent(props: { - onSomeEvent( - event: ComplexEventObj, - moreArgs: ComplexArgs - ): SomeWeirdReturnType; -}) { - /* ... */ -} - -// my-consuming-component.tsx -export function MyConsumingComponent() { - // event and moreArgs are contextually typed along with the return value - const theHandler: Props["onSomeEvent"] = ( - event, - moreArgs - ) => {}; - return ; -} +// a Modal component defined elsewhere +const defaultProps: React.ComponentProps = { + title: "Hello World", + visible: true, + onClick: jest.fn(), +}; ``` +There are advanced edge cases if you want to extract the prop types of a component taking into account internal props, `propTypes`, and `defaultProps` - [check our issue here for helper utilities that resolve these](https://github.com/typescript-cheatsheets/react/issues/63). + ## Props: Render Props > Advice: Where possible, you should try to use Hooks instead of Render Props. We include this merely for completeness.