'Does TypeScript support constructor with object initializer?
For example, in c#, we have this snippet:
class OrderLine
{
public OrderLine(){
OrderId ="1",
ItemTitle ="2"
Console.WriteLine("constructing");
}
public string Platform { get; set; }
public string OrderId { get; set; }
public string ItemTitle { get; set; }
}
public static void Main()
{
var ol = new OrderLine
{
Platform ="p"
};
Console.WriteLine(ol.Platform);
}
In Typescript, if I use {} to initialize an object, I won't be able to call the constrcuor which can give me some default value and do something else. if I use new key word to do some default construction, my compiler doesn't allow me to use object initializer(I am using angular 6), and I have to call ol.Platform to assign property value. When I have several properties to set value, writing multiple "ol." is not as fast as to use the object initializer syntax. is there a better way?
Solution 1:[1]
You can have the constructor accept an object for which each of its properties get assigned to the instance with Object.assign
:
type Init = {
age: number;
gender: string;
};
class Foo {
public name: string;
public age: number | undefined;
public gender: string | undefined;
constructor(name: string, init?: Partial<Init>) {
this.name = name;
if (init) {
Object.assign(this, init);
}
}
}
const f = new Foo('bob', { age: 10 });
Solution 2:[2]
Adding this to the original answer ...
You can define init
as the same type, i.e. Partial<Foo>
@RoutingKey('abc')
class Foo {
public name: string | undefined;
public age: number | undefined;
public gender: string | undefined;
constructor(init?: Partial<Foo>) {
if (init) {
Object.assign(this, init);
}
}
}
const foo = new Foo({ name: 'something' });
This was useful to me as I had to call new
to get the constructor decorator @RoutingKey()
to fire
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | CertainPerformance |
Solution 2 |