Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically apply argument to class constructor?

I have an es6 class User and a global function map() given below:

class  User {
  constructor(public name: string) {}
}

const map = <T, R>(project: (value: T) => R) => {}

Instead of writing the following:

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

I want to (somehow) write something like:

map(new User)

I am not sure if this is possible or not.

like image 468
Goga Koreli Avatar asked Dec 28 '18 10:12

Goga Koreli


People also ask

How do you pass a parameter to a constructor in Python?

Creating the constructor in python We can pass any number of arguments at the time of creating the class object, depending upon the __init__() definition. It is mostly used to initialize the class attributes. Every class must have a constructor, even if it simply relies on the default constructor.

Do class constructors have arguments?

If we don't define a constructor in a class, then the compiler creates a default constructor(with no arguments) for the class. And if we write a constructor with arguments or no arguments then the compiler does not create a default constructor.

How do you pass value from the constructor of a child class to the constructor of a base class in C#?

If we want to pass arguments to the base class's constructor from the constructor of the child class, we have to use the base keyword in C#. The base keyword specifies which constructor of the base class should be called when an instance of the child class is created.

What is this () in constructor in C#?

The “this” keyword in C# is used to refer to the current instance of the class. It is also used to differentiate between the method parameters and class fields if they both have the same name. Another usage of “this” keyword is to call another constructor from a constructor in the same class.


2 Answers

You can create a static function in your class that takes the value param and returns a new User:

class User {
  static createUser(value) {
    return new User(value)
  }
}

And then use:

map(User.createUser)
like image 60
Baboo Avatar answered Sep 25 '22 12:09

Baboo


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));
like image 41
Titian Cernicova-Dragomir Avatar answered Sep 22 '22 12:09

Titian Cernicova-Dragomir