1

I have a curious question, because I'm gonna build a class, which should return the same value all the time when I call another method. I will show you an example:

class Vendor {
    sendSignal() {
        return 'Sent';
    }
    [key: string]: Function;
}
let vendor = new Vendor();

Now I call a non-existent method like:

vendor.sendRocket() //Output: 'Sent'
vendor.sendCovfefe(); //Output 'Sent'

And you see how it should work, even if I didn't place those methods in my class, they should return the value from the sendSignal method.

I know it might not work in Typescript so well. So does it work at all?

tk421
  • 5,775
  • 6
  • 23
  • 34
Dakito
  • 347
  • 1
  • 4
  • 9
  • 3
    Possible duplicate of [JavaScript getter for all properties](https://stackoverflow.com/questions/994143/javascript-getter-for-all-properties) – amitdigga Feb 27 '19 at 19:23

1 Answers1

1

I think you will need a Proxy to get this kind of behavior. It's possible to implement although I'm sure there are edge cases you need to consider. Something like this:

class Vendor {
    // make a proxy instead of a different object
    constructor() {
        return new Proxy({} as Vendor, {
            get() {
                return Vendor.prototype.sendSignal;
            }
        })
    }
    sendSignal() {
        return 'Sent';
    }
    [key: string]: () => string;
}
let vendor = new Vendor();
console.log(vendor.sendRocket()) // Output: 'Sent'
console.log(vendor.sendCovfefe()); //Output 'Sent'

Hope that helps. Again, there are likely edge cases (e.g., vendor instanceof Vendor === false) that can be cleaned up if you really need it. Anyway, good luck!

jcalz
  • 264,269
  • 27
  • 359
  • 360