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.
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.
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.
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.
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.
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)
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With