简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM