使用值实例化typescript类实例(对象初始化)

时间:2018-03-06 16:22:02

标签: typescript

因此在c#中,您可以使用object initializer语法实例化具有值的类。在TypeScript中,它似乎不是同一种对象初始化器语法。我发现您可以使用以下两种方法初始化值:

构造函数初始化:

class MyClass {
  constructor(num: number, str: string) {
    this.numProperty = num;
    this.strProperty = str;
  }
  numProperty: number;
  strProperty: string;
}

let myClassInstance = new MyClass(100, 'hello');

对象类型投射:

class MyClass {
  numProperty: number;
  strProperty: string;
}

let myClassInstance = <MyClass>{
  numProperty: 100,
  strProperty: 'hello'
};

虽然我喜欢在TypeScript中使用对象类型转换语法,但它只适用于没有您需要使用的方法的简单DTO类。这是因为强制转换实际上并没有创建您要投射到的类类型的对象。

还有其他方法可以在TypeScript中进行对象初始化吗?

1 个答案:

答案 0 :(得分:3)

如果您喜欢“类型转换”方法但想要获取该类的实际实例,则可以使用Object.assign或辅助函数,如下所示:

function init<T>(ctor: new () => T, props: Partial<T>): T {
  return Object.assign(new ctor(), props);
}

你可以像这样使用它:

class MyClass {
  public numProperty: number = 0;
  public strProperty: string = "";
  public worksWithMethodsToo() {
     console.log("numProperty: "+this.numProperty);
     console.log("strProperty: "+this.strProperty);
  }
}

let myClassInstance = init(MyClass, { numProperty: 100, strProperty: 'hello' });
myClassInstance.worksWithMethodsToo(); // works

还有一个版本的“构造函数初始化”方法,它允许通过对构造函数签名中的参数使用publicprivate等访问修饰符来更轻松地编写构造函数,以创建所谓的parameter properties

class MyClass {
  // body of constructor is not necessary
  constructor(public numProperty: number, public strProperty: string) {}
}

let myClassInstance = new MyClass(100, 'hello');

这与原始的MyClass大致相同(我想参数名称不同),但它会减少样板代码。

这有帮助吗?祝你好运。

相关问题