How to add types to an interface from another interface or extend types in TypeScript?
How to add types to an interface from another interface or extend types in TypeScript?
In TypeScript, interfaces are a powerful way to define contracts within your code and ensure that the objects adhere to a specific structure. When it comes to adding types from one interface to another or extending types, TypeScript provides several mechanisms to achieve this, primarily through interface inheritance and type intersection.
Interface inheritance allows one interface to extend another, effectively inheriting its properties and methods. This is done using the extends
keyword. When an interface extends another, it incorporates the properties of the parent interface in addition to its own properties. This mechanism is useful for creating a hierarchy of interfaces that build upon each other, adding more specific properties or methods as the hierarchy progresses.
interface Mailable {
send(email: string): boolean;
queue(email: string): boolean;
}
interface FutureMailable extends Mailable {
later(email: string, after: number): boolean;
}
In the example above, FutureMailable
extends Mailable
, meaning it has the send
and queue
methods from Mailable
, plus its own later
method[17].
TypeScript also allows the combination of types through intersection types. While not directly related to interfaces, intersection types can be used to combine multiple types, including interfaces, into a new type that includes all properties of the combined types. This is achieved using the &
operator.
interface Event {
name: string;
dateCreated: string;
}
interface UserEvent {
UserId: string;
}
type ExtendedEvent = Event & UserEvent;
In this example, ExtendedEvent
is a type that includes all properties from both Event
and UserEvent
[1].
Another way to add or extend types in interfaces is through the use of generics. Generics provide a way to create reusable components by creating a placeholder for a type that is specified when the component is used.
interface Repository<T> {
findById(id: string): ...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào