小编Sub*_*kha的帖子

有没有办法在 TypeScript 中将多种类型的数据放入数组中?

这是我要问的一个例子。
假设我们有两个接口,Cats并且Dogs。如何制作一个可以同时容纳Cats和 的数组Dogs

interface Cats {
  name: string;
  age: number;
}

interface Dog {
  owner: string;
}

const cat1: Cats = {
  name: "Jimmy",
  age: 5,
}

const dog1: Dogs = {
  owner: "Bobby",
}

// The line below doesn't work how I think it would work
const animalsList: Array<Cats> | Array<Dogs> = [cat1, dog1];
Run Code Online (Sandbox Code Playgroud)

该变量animalsList应该能够同时包含CatsDogs,但我收到诸如
“类型Dogs无法分配给类型Array<Cats>”之类的错误

arrays types conditional-statements type-declaration typescript

4
推荐指数
1
解决办法
5700
查看次数