You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript类型声明问题:如何声明多类型组成的数组类型?

问题分析与解决方案

你的错误根源在于类型声明的层级混淆:

  • 你把Animal定义成了(Dog | Cat)[],也就是「元素为Dog/Cat的数组类型」
  • 但你又声明animals: Animal[],这等于把animals的类型变成了「数组的数组」((Dog | Cat)[][])
  • 所以当你尝试push单个Dog对象时,TypeScript会报错——它期望你传入的是一个(Dog | Cat)[]类型的数组,而非单个动物实例

正确的两种声明方式

方式一:将Animal定义为单个动物的联合类型(更常用)

这种方式更符合语义,Animal代表单个动物,数组用Animal[]表示:

export interface Dog {
  woof: boolean;
}

export interface Cat {
  meow: boolean;
}

// 单个动物的联合类型
export type Animal = Dog | Cat;

// 动物数组
let animals: Animal[] = [];

let dog: Dog = { woof: true };
animals.push(dog); // 无错误,正常运行

方式二:保留Animal作为数组类型的命名

如果你想让Animal直接代表动物数组,那么声明变量时不需要再加[]:

export interface Dog {
  woof: boolean;
}

export interface Cat {
  meow: boolean;
}

// 动物数组类型
export type Animal = (Dog | Cat)[];

// 直接使用Animal类型声明数组
let animals: Animal = [];

let dog: Dog = { woof: true };
animals.push(dog); // 无错误,正常运行

内容的提问来源于stack exchange,提问作者tariq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 21:22:08