[Typescript] Using Type and not Interface in TypeScript
Nên dùng Type hay Interface trong Typescript
TypeScript offers two main ways to define custom data structures: type
and interface
. Both serve similar purposes, but there are differences between them that influence when and why you might choose one over the other.
When to Use type:
Unions and Intersections: If you need to create complex types by combining multiple types using union (
|
) or intersection (&
) operators,type
is the way to go.type
is more flexible when it comes to creating complex and flexible type compositions.type Person = { name: string; age: number }; type Address = { city: string; postalCode: string }; type Contact = Person & Address;
Primitive Types: When defining simple types like strings, numbers, booleans, or literal types,
type
is often preferred.type Status = "active" | "inactive";
Mapped Types: If you want to create new types based on the properties of existing types,
type
is used for mapped types.type Optional<T> = { [P in keyof T]?: T[P] };
Utility Types: TypeScript provides built-in utility types like
Partial
,Record
,Pick
, andOmit
that work naturally withtype
.type PartialPerson = Partial<Person>; type RecordOfPersons = Record<string, Person>;
When to Use interface:
Object Shapes: If you're defining the shape of an object, especially one that represents a class or an instance,
interface
is a common choice. It's more suited for describing the blueprint of an object.interface Person { name: string; age: number; }
Class Implementations: When defining the structure of a class,
interface
is preferred as it can be extended or implemented by classes.interface Animal { name: string; speak(): void; } class Dog implements Animal { constructor(public name: string) {} speak() { console.log(`${this.name} barks.`); } }
Extending Interfaces:
interface
can be easily extended to create new interfaces that inherit properties and methods from existing ones.interface Employee { name: string; } interface Manager extends Employee { department: string; }