Strongly Typed Component Props
Explore how to create flexible and type-safe polymorphic React components by explicitly managing prop types. Understand the use of TypeScript utility types like Omit and keyof to prevent type conflicts and enforce correct HTML attribute typings.
We'll cover the following...
Having done the necessary refactoring, we will now continue with our solution. What we have now actually works. We’ve explicitly typed the color prop. What could go wrong?
Problem with composing component props
The color attribute is also be a valid attribute for numerous HTML tags. This was the case pre-HTML5. So, if we remove the color from our type definition, it’ll be accepted by our component as any valid string, courtesy of the React.ComponentPropsWithoutRef type.
Look at this in the playground below, where color has been removed from the component prop. Note how TypeScript still allows us to pass any color string value to the component.
Click "Run" ...