Cannot invoke an expression whose type lacks a call signature
Solution 1:
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[]
.
Solution 2:
As mentioned in the github issue originally linked by @peter in the comments:
const freshFruits = (fruits as (Apple | Pear)[]).filter((fruit: (Apple | Pear)) => !fruit.isDecayed);
Solution 3:
Perhaps create a shared Fruit
interface that provides isDecayed. fruits
is now of type Fruit[]
so the type can be explicit. Like this:
interface Fruit {
isDecayed: boolean;
}
interface Apple extends Fruit {
color: string;
}
interface Pear extends Fruit {
weight: number;
}
interface FruitBasket {
apples: Apple[];
pears: Pear[];
}
const fruitBasket: FruitBasket = { apples: [], pears: [] };
const key: keyof FruitBasket = Math.random() > 0.5 ? 'apples': 'pears';
const fruits: Fruit[] = fruitBasket[key];
const freshFruits = fruits.filter((fruit) => !fruit.isDecayed);