DEV Community

official_dulin
official_dulin

Posted on

3 2

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?

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more