DEV Community

official_dulin
official_dulin

Posted on

 

Use TypeScript interface extends and type composition semantically

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;
}
Enter fullscreen mode Exit fullscreen mode

Now you have two choice to pack these parameters.

Option 1:

interface GetUsersByPageRequestDTO extends Pagination {
  channelCode?: string;
}
Enter fullscreen mode Exit fullscreen mode

Option 2:

type GetUsersByPageRequestDTO = {
  channelCode?: string;
} & Pagination;
Enter fullscreen mode Exit fullscreen mode

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)

An Animated Guide to Node.js Event Loop

>> Check out this classic DEV post <<