In TypeScript, both type
and interface
can be used to define the shape of an object, but there are specific benefits to using type
.
Union Types: type
allows you to create union types.
type Status = 'success' | 'error' | 'loading';
Composability: type
can be used to compose more complex types.
type Point = { x: number; y: number };
type Circle = Point & { radius: number };
Mapped Types: type
can create mapped types for advanced scenarios.
type ReadOnly<T> = {
readonly [P in keyof T]: T[P];
};
type
can represent any kind of type, not just object shapes.type
is simpler when working with unions and intersections.type
can lead to more readable code, especially with complex type compositions.Using type
for a component's props:
type MyComponentProps = {
title: string;
isVisible: boolean;
};
const MyComponent: FC<MyComponentProps> = ({ title, isVisible }) => {
if (!isVisible) return null;
return (
<div>
<h1>{title}</h1>
</div>
);
};
export { MyComponent };