|
| 1 | +--- |
| 2 | +title: ComponentProps<ElementType> |
| 3 | +--- |
| 4 | + |
| 5 | +`ComponentProps<ElementType>` constructs a type with all valid props of an element or inferred props of a component. |
| 6 | + |
| 7 | +:::note |
| 8 | + |
| 9 | +Prefer `ComponentPropsWithRef<ElementType>` if ref is forwarded and `ComponentPropsWithoutRef<ElementType>` when ref is not forwarded. |
| 10 | + |
| 11 | +::: |
| 12 | + |
| 13 | +## Parameters |
| 14 | + |
| 15 | +- `ElementType`: An element type. Examples include: |
| 16 | + - An HTML or SVG element string literal such as `"div"`, `"h1"` or `"path"`. |
| 17 | + - A component type, such as `typeof Component`. |
| 18 | + |
| 19 | +## Usage |
| 20 | + |
| 21 | +### Get all valid props of an element |
| 22 | + |
| 23 | +`ComponentProps<ElementType>` can be used to create a type that includes all valid `div` props. |
| 24 | + |
| 25 | +```tsx |
| 26 | +interface Props extends ComponentProps<"div"> { |
| 27 | + text: string; |
| 28 | +} |
| 29 | + |
| 30 | +function Component({ className, children, text, ...props }: Props) { |
| 31 | + // `props` includes `text` in addition to all valid `div` props |
| 32 | +} |
| 33 | +``` |
| 34 | + |
| 35 | +### Infer component props type |
| 36 | + |
| 37 | +In some cases, you might want to infer the type of a component's props. |
| 38 | + |
| 39 | +```tsx |
| 40 | +interface Props { |
| 41 | + text: string; |
| 42 | +} |
| 43 | + |
| 44 | +function Component(props: Props) { |
| 45 | + // ... |
| 46 | +} |
| 47 | + |
| 48 | +type MyType = ComponentProps<typeof Component>; |
| 49 | +// ^? type MyType = Props |
| 50 | +``` |
| 51 | + |
| 52 | +#### Infer specific prop type |
| 53 | + |
| 54 | +The type of a specific prop can also be inferred this way. Let's say you are using an `<Icon>` component from a component library. The component takes a `name` prop that determines what icon is shown. You need to use the type of `name` in your app, but it's not made available by the library. You could create a custom type: |
| 55 | + |
| 56 | +```tsx |
| 57 | +type IconName = "warning" | "checkmark"; |
| 58 | +``` |
| 59 | + |
| 60 | +However, this type if not really reflecting the actual set of icons made available by the library. A better solution is to infer the type: |
| 61 | + |
| 62 | +```tsx |
| 63 | +import { Icon } from "component-library"; |
| 64 | + |
| 65 | +type IconName = ComponentProps<typeof Icon>["name"]; |
| 66 | +// ^? type IconName = "warning" | "checkmark" |
| 67 | +``` |
| 68 | + |
| 69 | +You can also use the `Pick<Type, Keys>` utility type to accomplish the same thing: |
| 70 | + |
| 71 | +```tsx |
| 72 | +import { Icon } from "component-library"; |
| 73 | + |
| 74 | +type IconName = Pick<ComponentProps<typeof Icon>, "name">; |
| 75 | +// ^? type IconName = "warning" | "checkmark" |
| 76 | +``` |
0 commit comments