What is type? In TypeScript, type is a way to define a custom type. It can be used to create complex types from primitive types or other types. With type, you can define types for objects, unions, intersections, and even more complex types. Example:
// Defining a type for an object
type Person = {
name: string;
age: number;
};
// Using the type
const person: Person = {
name: "João",
age: 25,
};
When to use type? Unions and Intersections: When you need to combine types, type is a good choice. It allows you to create unions (one type or another) and intersections (combination of types).
type ID = string | number; // Union
type Coordinates = { x: number } & { y: number }; // Intersection
Developer tip: If you need to define types that are not just objects, like unions of primitive types, type is more flexible.
What is interface? Interface is another way to define the shape of an object in TypeScript. It is mainly used to define contracts for objects, meaning it specifies which properties and methods an object must have. A class/object that implements an interface must have all the fields and methods (except those explicitly marked as optional). Therefore, interfaces are used for type-checking.
Example:
// Defining an interface for an object
interface Car {
brand: string;
year: number;
}
// Using the interface
const car: Car = {
brand: "Toyota",
year: 2020,
};
Key Differences
1- Extension: interface can be extended by other interfaces, while type can use intersections to combine types, but cannot be extended in the same way.
2- Unions: type can create unions of types, whereas interface cannot.
3- Class Implementation: interface is more commonly used to define contracts that classes should follow.
For more informations:
If you want to dive deeper, I recommend exploring the official TypeScript documentation, where you'll find a playground with examples and detailed explanations about type and interface."
Top comments (0)