TypeScript supports structural typing (also called duck typing), meaning that types are compatible when they share the same members. Your problem is that Apple
and Pear
don't share all their members, which means that they are not compatible. They are however compatible to another type that has only the isDecayed: boolean
member. Because of structural typing, you don' need to inherit Apple
and Pear
from such an interface.
There are different ways to assign such a compatible type:
Assign type during variable declaration
This statement is implicitly typed to Apple[] | Pear[]
:
const fruits = fruitBasket[key];
You can simply use a compatible type explicitly in in your variable declaration:
const fruits: { isDecayed: boolean }[] = fruitBasket[key];
For additional reusability, you can also define the type first and then use it in your declaration (note that the Apple
and Pear
interfaces don't need to be changed):
type Fruit = { isDecayed: boolean };
const fruits: Fruit[] = fruitBasket[key];
Cast to compatible type for the operation
The problem with the given solution is that it changes the type of the fruits
variable. This might not be what you want. To avoid this, you can narrow the array down to a compatible type before the operation and then set the type back to the same type as fruits
:
const fruits: fruitBasket[key];
const freshFruits = (fruits as { isDecayed: boolean }[]).filter(fruit => !fruit.isDecayed) as typeof fruits;
Or with the reusable Fruit
type:
type Fruit = { isDecayed: boolean };
const fruits: fruitBasket[key];
const freshFruits = (fruits as Fruit[]).filter(fruit => !fruit.isDecayed) as typeof fruits;
The advantage of this solution is that both, fruits
and freshFruits
will be of type Apple[] | Pear[]
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…