TypeScript 中组合多个接口类型的方法:交叉与联合

作者:异步漫步

时间:2026-11-01

浏览:227

本文介绍在 TypeScript 中如何组合多个接口类型。通过交叉类型(&)合并所有属性,或使用联合类型(|)实现多选一。结合 Vue 3 的 defineProps 示例,展示如何灵活运用这两种方式处理复杂类型声明。

文章目录
<script setup lang="ts"> 
interface Props { foo: string bar?: number } 
const props = defineProps<Props>() 
</script> 

当定义多个接口时,在声明类型时是否可以将多种类型进行混合组合?

答案是肯定的。在 TypeScript 中,您可以利用交叉类型(&)或联合类型(|)来组合多个接口,从而实现多类型混合的效果。在 Vue 3 的 defineProps 配置中,同样支持这种组合方式。

1. 使用交叉类型(&)

若需将多个接口的属性合并为一个整体(即所有接口的属性都必须存在),应使用交叉类型。

例如,假设有以下两个接口定义:

interface FooProps {
  foo: string
}

interface BarProps {
  bar?: number
}

interface BazProps {
  baz: boolean
}

可以通过交叉类型将这些接口组合为一个新的类型:

<script setup lang="ts">
interface FooProps {
  foo: string
}

interface BarProps {
  bar?: number
}

interface BazProps {
  baz: boolean
}

const props = defineProps<FooProps & BarProps & BazProps>()
</script>

在此示例中,props 将包含 foo、bar 和 baz 属性,其中 bar 为可选属性。

2. 使用联合类型(|)

若希望 props 可以是多个接口中的任意一种,则可使用联合类型。

示例如下:

<script setup lang="ts">
interface FooProps {
  foo: string
}

interface BarProps {
  bar?: number
}

const props = defineProps<FooProps | BarProps>()
</script>

在此例中,props 可以是 FooProps 或 BarProps 中的任意一种。这意味着,props 要么拥有 foo 属性,要么拥有 bar 属性,且 bar 为可选属性。

3. 组合多个类型的示例

您也可以结合使用交叉类型和联合类型,以实现更复杂的类型组合逻辑。

例如:

<script setup lang="ts">
interface FooProps {
  foo: string
}

interface BarProps {
  bar?: number
}

interface BazProps {
  baz: boolean
}

const props = defineProps<(FooProps & BarProps) | BazProps>()
</script>

该示例表示 props 要么同时包含 foo 和 bar 属性,要么仅包含 baz 属性。

小结

  • 交叉类型(&):适用于将多个接口的属性合并为一个类型,要求所有属性均存在。
  • 联合类型(|):适用于使 props 能够接受多个类型中的任意一个。
  • 您可以根据实际需求,选择使用交叉类型、联合类型,或将两者结合使用。

本文关于 TypeScript 定义多个接口类型声明方式的介绍到此结束。如需了解更多相关 TypeScript 接口类型声明内容,请搜索本站往期文章或继续浏览后续相关文章。感谢大家的支持!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章