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

Is there a way to put multiple types of data in an array in TypeScript?

这是我要问的一个例子。
假设我们有两个接口,CatsDogs。我如何制作一个可以容纳 CatsDogs 的数组?

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];

变量 animalsList 应该可以同时包含 CatsDogs,但我收到类似
的错误 “无法将类型 Dogs 分配给类型 Array<Cats>

如果我没看错这个问题,你希望能够制作一个既能容纳猫又能容纳狗的数组。当前的方式 Array<Cats> | Array<Dogs> 意味着您可以拥有 a) 只能容纳猫的数组,或 b) 只能容纳狗的数组。

要解决此问题,您需要有一个可以容纳两者的数组。方法如下:

public animalsList: Array<Cats | Dogs>;

管道的新位置(|)说明这个Array是一个可以同时容纳Cats和Dogs的数组。

@cherryblossom提到的另一种选择是:

public animalsList: (Cats | Dogs)[];

工作方式类似

这是一个完整的示例:

// Welcome to the TypeScript Playground, this is a website
// which gives you a chance to write, share and learn TypeScript.

// You could think of it in three ways:
//
//  - A place to learn TypeScript in a place where nothing can break
//  - A place to experiment with TypeScript syntax, and share the URLs with others
//  - A sandbox to experiment with different compiler features of TypeScript

const anExampleVariable = "Hello World"
console.log(anExampleVariable)

// To learn more about the language, click above in "Examples" or "What's New".
// Otherwise, get started by removing these comments and the world is your playground.
  
class Cats {
    private name: String;
    constructor(name: String) {
        this.name = name;
    }
    public dump() { console.log(`I am cat ${this.name}`); }
}
class Dogs {
    private name: String;
    constructor(name: String) {
        this.name = name;
    }
    public dump() { console.log(`I am dog ${this.name}`); }
}

class Test {
    public animalsList : Array<Cats> | Array<Dogs> = Array();
}

const t = new Test();
t.animalsList = Array(new Cats('cat1'), new Cats('cat2'));
t.animalsList.forEach((v, i) => { v.dump(); });

t.animalsList = Array(new Dogs('pluto'), new Dogs('goofy'));
t.animalsList.forEach((v, i) => { v.dump(); });

// The following line fails
//t.animalsList = Array(new Dogs('pluto'), new Cats('cat2'));
//t.animalsList.forEach((v, i) => { v.dump(); });

你可以在https://www.typescriptlang.org/play

上试试