How to automatically apply argument to class constructor?

  • A+
Category:Languages

I want to instead of writing following:

map((value) => new User(value)) 

Somehow write something like this:

map(new User) 

User is es6 class:

class  User {   constructor(public name: string) {} }  const map = <T, R>(project: (value: T) => R) => {} 

I am not sure if this is possible or not.

 


You can't do it directly. If you control the target function (ie it's not the stock map function) you can have it take a constructor instead of the function:

class User { constructor(private id: number) { }} function map<TIn, T>(value: TIn, ctor: new (a: TIn) => T): T{     return new ctor(value) } map(10, User) 

Another more flexible solution is to use a helper function that transform the constructor into the desired function, although it's not much shorter then the original version:

class User { constructor(private id: number) { }} function ctor<TIn, T>(ctor: new (a: TIn) => T): (value: TIn) => T{     return value => new ctor(value) } [10, 11].map(ctor(User)); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: