Michael Moreno
Michael Moreno

Reputation: 1359

Adding custom method to Object.prototype in TypeScript

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?

Upvotes: 3

Views: 2493

Answers (1)

hgb123
hgb123

Reputation: 14901

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

Upvotes: 5

Related Questions