Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用 interface + type 混合设计,分工明确 #685

Open
981377660LMT opened this issue Jan 2, 2025 · 1 comment
Open

使用 interface + type 混合设计,分工明确 #685

981377660LMT opened this issue Jan 2, 2025 · 1 comment

Comments

@981377660LMT
Copy link
Owner

No description provided.

@981377660LMT
Copy link
Owner Author

  • interface:适合描述“对象结构”,可在多个地方声明并自动合并,特别适合对外暴露的 API、配置对象、类的形状等。
  • type:更灵活,可以写联合、交叉、条件类型等高级用法,也能定义函数类型或复杂的泛型类型工具。

示例:

interface ApiResponse {
  data: any
  status: number
}

// 可以声明合并
interface ApiResponse {
  message?: string
}

// 高级条件处理用 type
type ExtractData<T extends ApiResponse> = T['data'] extends infer D ? D : never
  • 这样既利用了接口可声明合并的特性,又在需要条件/高级泛型时用 type 发挥灵活性。
  • 大多数团队的最佳实践也是“基础对象结构 -> interface,高级操作 / 组合 -> type”。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant