0

An example of what I want to do in C# looks like this:

namespace SharedFramework
{
    public static class Extensions
    {
        public static void SomeExtension(this object obj)
        {
            //whatever
        }
    }
}
Programmer Paul
  • 488
  • 1
  • 3
  • 13
  • 1
    It is possible, but it's a bad idea: https://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice – Alex Wayne Jan 04 '22 at 22:25
  • I wanted to also acknowledge that doing this is a bad idea as described by others. It can screw things up in really weird ways. In my case I'm just goofing around – Programmer Paul Jan 10 '22 at 21:02

1 Answers1

1

As Alex Wayne notes, this is generally a bad idea unless you are just using it for polyfills.

But yes, this can be done in Typescript because interfaces are open for extension (docs link). So you just need to extend the Object interface when you add something to Object.prototype; or you can extend other interfaces like Array if you don't want to affect every object.

interface Object {
    foo(): void;
}

Object.prototype.foo = () => console.log('bar');

const a: {} = {};
a.foo();

Playground Link

kaya3
  • 47,440
  • 4
  • 68
  • 97
  • 1
    Thank you for the answer! This is what I was looking for. The only catch I'm noticing is that Intellisense in Visual Studio, Visual Studio Code, and even the Playground do not suggest the "foo" when you type "a." It's not in the list, but it does seem to compile. Is there an additional trick to get the Intellisense to show the method? – Programmer Paul Jan 05 '22 at 21:58