0

I was wondering if there is the possibility to create methods, with the same body, in TypeScript. In JavaScript, I can extend the class with 'Prototype':

var methods = [
  {
    'name' : 'f_1',
    'argumentsLength' : 1
  },
  {
    'name' : 'f_2',
    'argumentsLength' : 2
  }
];

var Person = function (name) {
  this.name = name;
};

for (var k = 0; k < methods.length; k++) {
  !function (fName, fParamsLength) {
    Person.prototype[fName] = function () {
      if (arguments.length !== fParamsLength) {
        throw new Error ('Wrong number of parameters.');
      }

      console.log ('Function name : ' + fName);
      for (var k = 0; k < arguments.length; k++) {
        console.log ('arguments[' + k + '] : ' + arguments[k]);
      }
      console.log ();
    };
  } (methods[k].name, methods[k].argumentsLength);
}

var p = new Person ('Jumbo');

p.f_1 (1);
p.f_2 (2, 3);

I cannot do the same in TypeScript. I have an error when I try to call the methods 'f_1' and 'f_2' since I didn't declare them explicitly.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
marco
  • 51
  • 3
  • Use `class` and `extends` in TypeScript to implement inheritance. – Michał Miszczyszyn Mar 22 '16 at 09:40
  • How does the inheritance solve my problem? I don't want to write several functions, with the same body. For this reason I'm searching a solution like the previous. – marco Mar 22 '16 at 14:00
  • I see now! Sorry I completely misunderstood your code after the first glance. I'll post an answer, hopefully my solution will work for you. – Michał Miszczyszyn Mar 22 '16 at 21:08
  • However, I need a little bit more information. Do you know the fields in advance, or are they somehow generated, eg. from a server? What's the use case of this, is this some kind of meta programming where methods are generated? – Michał Miszczyszyn Mar 22 '16 at 21:19
  • Take a look at http://stackoverflow.com/questions/16813118/extending-object-prototype-with-typescript – Marc Mar 23 '16 at 08:52

0 Answers0