TypeScript是否支持带有对象初始值设定项的构造函数



例如,在c#中,我们有以下代码段:

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); 
}

在Typescript中,如果我使用{}来初始化一个对象,我将无法调用construcor,它可以给我一些默认值并做其他事情。如果我使用新的关键字来进行一些默认构造,我的编译器不允许我使用对象初始值设定项(我使用的是angular 6(,我必须调用ol。用于分配属性值的平台。当我有几个属性要设置值时,编写多个"ol."并不像使用对象初始值设定项语法那样快。有更好的方法吗?

您可以让构造函数接受一个对象,该对象的每个属性都被分配给具有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 });

将其添加到原始答案中。。。

您可以将init定义为相同类型,即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' });

这对我很有用,因为我必须调用new才能让构造函数decorator@RoutingKey()启动

最新更新