问题描述
这是我要问的一个例子。
假设我们有两个接口,UTF-8
和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];
应该可以同时包含animalsList
和Cats
,但出现类似
的错误
“无法将类型Dogs
分配为类型Dogs
”
解决方法
如果我正确阅读了此问题,则希望能够制作一个既可以容纳猫又可以容纳狗的阵列。它们以目前的方式Array<Cats> | Array<Dogs>
表示您可以具有a)仅可容纳Cats的数组,或b)仅可容纳Dogs的数组。
要解决此问题,您需要具有一个可以容纳两者的数组。做到这一点的方法如下:
public animalsList: Array<Cats | Dogs>;
管道的新位置(|
)表明此数组是可以同时容纳Cat和Dog的数组。
这里是完整样本:
// 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(); });
上尝试