What is the difference between these statements (interface vs type) in TypeScript? interface X { a: number b: string } type X = { a: number b: string };
In TypeScript, both interface and type can be used to define object shapes, but they have some differences in terms of their features and usage. Here's a comparison using examples:
- Using
interface: An interface is a way to define a contract that objects must adhere to. It's often used to describe the shape of objects and is suitable for defining contracts that classes or objects implement.
typescript
interface Person {
name: string;
age: number;
}
const person: Person = {
name: "Alice",
age: 30
};
- Using
type: A type alias (defined withtype) is a way to create a new name for a type. It's often used to simplify complex type expressions or to create union types and intersections.
typescript
type Person = {
name: string;
age: number;
};
const person: Person = {
name: "Bob",
age: 25
};
Both interface and type can describe object shapes, but there are some distinctions:
Extending/Implementing:
interfacecan be extended from other interfaces using theextendskeyword.typecan represent union types, intersection types, and mapped types more flexibly.
Implements Class:
interfacecan be implemented by classes in TypeScript, aiding in enforcing class structure.typecannot be directly implemented by classes.
Declaration Merging:
interfacesupports declaration merging, meaning you can extend an existing interface in different parts of your code.typedoes not support declaration merging.
Compatibility:
typecan define simple type aliases, whileinterfacecan represent more complex structures, including call signatures, index signatures, etc.
For most use cases, both interface and type are interchangeable when defining object shapes. Choose based on the specific needs of your codebase. If you need to extend from other interfaces, enforce class implementations, or use declaration merging, interface might be more suitable. If you need more flexibility in creating type aliases, unions, and intersections, type might be more appropriate.
Comments
Post a Comment