Adding custom method to Object.prototype in TypeScript

Viewed 28

I have the following code:

Object.prototype.custom = function() {
    return this
}

It works just fine in JavaScript, but when I put it in TypeScript, I get this error:

Property 'custom' does not exist on type 'Object'.ts(2339)

How can I bypass or solve this complaint?

1 Answers

For the sake of the experiment (not advised in production, IMO), you could either ignore it or extend Object (aka augmentation)

// @ts-ignore
Object.prototype.custom = function() {
    return this
}

interface Object {
  custom2(): Object;
}

Object.prototype.custom2 = function() {
    return this
}

TS playground

Related