Consider below example, you have an API which accepts three parameters: current
, pageSize
and channelCode
.
interface Pagination {
current: number;
pageSize: number;
}
interface GetUsersByPageRequestDTO {
channelCode?: string;
}
Now you have two choice to pack these parameters.
Option 1:
interface GetUsersByPageRequestDTO extends Pagination {
channelCode?: string;
}
Option 2:
type GetUsersByPageRequestDTO = {
channelCode?: string;
} & Pagination;
Which one will you choose? Inheritance or composition?
For me, I will choose option 2, use intersection type(type composition). Because using inheritance requires semantic correctness. Which means the two need to have is-a relationship. E.g. Bear is an animal. So bear interface can extend animal interface.
Apparently, GetUsersByPageRequestDTO
is NOT a Pagination
.
So we know the difference between interface
and type
, but we also have to pay attention to the semantic correctness, not only to get the final correct shape, right?
Top comments (0)