Sometimes, we want to fix the ‘Cannot invoke an expression whose type lacks a call signature’ error in TypeScript.
In this article, we’ll look at how to fix the ‘Cannot invoke an expression whose type lacks a call signature’ error in TypeScript.
How to fix the ‘Cannot invoke an expression whose type lacks a call signature’ error in TypeScript?
To fix the ‘Cannot invoke an expression whose type lacks a call signature’ error in TypeScript, we can cast the types of the variable so that the TypeScript compiler knows that the types of the object are compatible with the objects we have.
For instance, we write
interface Apple {
color: string;
isDecayed: boolean;
}
interface Pear {
weight: number;
isDecayed: boolean;
}
//...
const freshFruits = (fruits as (Apple | Pear)[]).filter(
(fruit: Apple | Pear) => !fruit.isDecayed
);
to cast the fruits
array to type (Apple | Pear)[]
so that the TypeScript compiler knows the fruits
has objects that are either of type Apple
or type Pear
.
Likewise, we set the fruit
parameter in the callback to Apple | Pear
so that the TypeScript compiler knows that fruit
is either an Apple
or a Pear
.
Then we can access the isDecayed
property without errors since it’s specified in both interfaces.
Conclusion
To fix the ‘Cannot invoke an expression whose type lacks a call signature’ error in TypeScript, we can cast the types of the variable so that the TypeScript compiler knows that the types of the object are compatible with the objects we have.