How can you solve a problem that inheritance solves in an alternative way? What is composition in the context of TypeScript and React?
sobes.tech AI
Answer from AI
Inheritance is a mechanism where one class or component extends another, inheriting its properties and methods. An alternative to inheritance is composition — building complex objects from simpler ones, combining their functionalities.
In the context of TypeScript and React, composition means that instead of creating class hierarchies, we create components that accept other components or functions as props and combine them to achieve the desired behavior.
Example of composition in React:
type ButtonProps = { onClick: () => void; children: React.ReactNode };
const Button: React.FC<ButtonProps> = ({ onClick, children }) => (
<button onClick={onClick}>{children}</button>
);
const IconButton: React.FC<{ icon: React.ReactNode; onClick: () => void }> = ({ icon, onClick }) => (
<Button onClick={onClick}>
{icon}
</Button>
);
Here, IconButton does not inherit from Button, but uses it internally, passing the necessary props. This increases flexibility and reusability.
In TypeScript, composition is also often implemented through interface merging and passing functions as parameters, which allows creating more modular and easily maintainable code.