Sometimes, we may run into the ‘TypeError: X.prototype.y called on incompatible type’ when we’re developing JavaScript apps.
In this article, we’ll look at how to fix the ‘TypeError: X.prototype.y called on incompatible type’ when we’re developing JavaScript apps.
Fix the ‘TypeError: X.prototype.y called on incompatible type’ When Developing JavaScript Apps
To fix the ‘TypeError: X.prototype.y called on incompatible type’ when we’re developing JavaScript apps, we should make sure that we’re calling Function.prototype.call
, Function.prototype.apply
, or Function.prototype.bind
with a this
value that is expected.
For instance, if we have:
const mySet = new Set;
['bar', 'baz'].forEach(mySet.add);
then we’ll get the error since the this
value in mySet.add
isn’t mySet
.
To fix this, we write:
const mySet = new Set;
['bar', 'baz'].forEach(mySet.add.bind(mySet));
to call bind
with mySet
to set mySet
as the value of this
in the mySet.add
method.
Conclusion
To fix the ‘TTypeError: X.prototype.y called on incompatible type’ when we’re developing JavaScript apps, we should make sure that we’re calling Function.prototype.call
, Function.prototype.apply
, or Function.prototype.bind
with a this
value that is expected.