3

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
  • 4
    Just don't add anything to global prototypes. (Don't do that in JS either!) Please, at least don't add anything to Object.prototype! Especially, don't make it enumerable!!! (Your code will add that property to every single object in existence, not even only the ones you manually create, and will even show up as a key in for..in loops, which is bad. Like, very bad. Doing that in your project is shooting yourself in the foot. Doing that in a library is shooting everyone in the foot.) Commented Sep 24, 2022 at 5:37

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Might want to link to docs on declaration merging as well as possibly talking about global augmentation if the code is in a module. But yeah, I agree that this is a BAD IDEA.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.