Here's an example of what I'm asking.
Say that we have two interfaces, Cats
and Dogs
. How can I make an array that can hold both Cats
and 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];
The variable animalsList
should be able to have both Cats
and Dogs
in it, but I am getting errors like
"Type Dogs
can not be assigned to type Array<Cats>
"
If I am reading this question correctly, you want to be able to make an Array that can hold both Cats and Dogs. The way it is currently Array<Cats> | Array<Dogs>
means that you can have either a) an array that can hold ONLY Cats, or b) an array that can hold ONLY Dogs.
To fix this, you need to have an array that can hold both. The way to do that is below:
public animalsList: Array<Cats | Dogs>;
The new location of the pipe (|
) tells that this Array is an array that can hold both Cats and Dogs at the same time.
Another option, mentioned by @cherryblossom, is this:
public animalsList: (Cats | Dogs)[];
Which works a similar way
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With