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.
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.