3

If a class does not implement a method, I want to handle the error raised and inject my own code, using the method name.

For example:

class Foo {
    def method_missing(methodName) {
        console.log(`${methodName} was called`);
    }
}

let foo = new Foo();
foo.bar(); // should print 'bar was called' in the console

In ruby, there is a method called method_missing on every class that provides this behavior. Can we get this in typescript, and how?

Anand
  • 3,690
  • 4
  • 33
  • 64

2 Answers2

0

No, TypeScript cannot do this.

Ryan Cavanaugh
  • 209,514
  • 56
  • 272
  • 235
0

It would be a bit more troublesome for TypeScript or JavaScript to have this, because in their world a method is just an Object attribute that holds a function reference instead of Ruby's way where the entire interface of an object consists of methods.

It might however be possible to implement something like this using a Proxy class. MDN describes it as follows:

The Proxy object allows you to create an object that can be used in place of the original object, but which may redefine fundamental Object operations like getting, setting, and defining properties. Proxy objects are commonly used to log property accesses, validate, format, or sanitize inputs, and so on.

I've heard that this feature supposedly could not be transpiled down to ECMAScript 5 platforms. I have not confirmed this yet, but better test this, so that you don't lock yourself out of platforms that are mandatory for you by considering this feature.

aef
  • 4,498
  • 7
  • 26
  • 44