【发布时间】:2018-08-14 14:06:05
【问题描述】:
因此,在 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 中进行对象初始化吗?
【问题讨论】:
-
注意对象类型转换选项。 TS 编译器会知道对象的类型是
MyClass,但 JavaScript 不会:myClassInstance instanceof MyClass将返回 false。
标签: typescript