attributes - Typescript idioms around adding properties to methods inline with the method definition -


are there idioms in typescript define properties methods in class inline method definition?

i'm looking similar .net attributes.

here's example of i've got far

class foocontroller {     foo(req: express.request, res: express.response) {         res.send(json.stringify({ loc: 'foocontroller::foo 2 here '+req.params.fooid }));     }     bar(req: express.request, res: express.response) {         res.send(json.stringify({ loc: 'foocontroller::bar here' }));     } } foocontroller.prototype.foo['route'] = '/foo/:fooid'; foocontroller.prototype.foo['verb'] = 'get'; foocontroller.prototype.bar['route'] = '/bar'; foocontroller.prototype.bar['verb'] = 'post'; 

where different function consume foocontroller , interrogate method attributes set routing table before of foocontroller methods invoked.

i don't distance between method definitions , property definitions, methods larger , supporting functions sit in between two.

is there better can here? if there different language features should using express other properties, i'm open that. i'm interested if solution retains type safety.

i did review build function object properties in typescript don't think solutions in there match because of late binding , object method requirements.

i'm using typescript compiler version 1.0.3 visual studio 2013 update 3.

the easiest way keep type safety on route methods define interface:

interface iroute {     (req: express.request, res: express.response): void;      route?: string;     verb?: string; } 

then define routing methods properties implement iroute interface. can use constructor define additional route , verb properties:

class foocontroller {      constructor(){         // type-safety on these properties:         this.foo.route = '/foo/:fooid';         this.foo.verb = 'get'          this.bar.route = '/bar';         this.bar.verb = 'post';     }      // use fat-arrow syntax bind scope instance.     foo: iroute = (req: express.request, res: express.response) => {         this.bar(req, res);     }      bar: iroute = (req: express.request, res: express.response) => {         // typescript knows additional properties on `this.foo`.         this.foo.route;          res.send(json.stringify({ loc: 'foocontroller::bar here' }));     }  } 

you might still have bit of "distance" between constructor , route methods, benefits are:

  • you gain type-safety
  • you don't have fiddle around foocontroller.prototype['foo']...
  • it's self-contained in class definition

here's above example in typescript playground.


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -