因此,在 c# 中,您可以使用对象初始值设定项语法使用值实例化一个类。在 TypeScript 中,似乎没有相同类型的对象初始值设定项语法。我发现您可以使用以下两种方法初始化值:
构造函数初始化:
class MyClass {
constructor(num: number, str: string) {
this.numProperty = num;
this.strProperty = str;
}
numProperty: number;
strProperty: string;
}
let myClassInstance = new MyClass(100, 'hello');
Run Code Online (Sandbox Code Playgroud)
对象类型转换:
class MyClass {
numProperty: number;
strProperty: string;
}
let myClassInstance = <MyClass>{
numProperty: 100,
strProperty: 'hello'
};
Run Code Online (Sandbox Code Playgroud)
虽然我喜欢在 TypeScript 中使用 Object Type Casting 语法,但它仅适用于没有您需要使用的方法的简单 DTO 类。这是因为转换实际上并没有创建您要转换到的类类型的对象。
还有其他方法可以在 TypeScript 中进行对象初始化吗?
如果您喜欢“类型转换”方法但想要获得该类的实际实例,则可以使用Object.assign或如下所示的辅助函数:
function init<T>(ctor: new () => T, props: Partial<T>): T {
return Object.assign(new ctor(), props);
}
Run Code Online (Sandbox Code Playgroud)
你可以像这样使用它:
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
Run Code Online (Sandbox Code Playgroud)
还有一个版本的“构造函数初始化”方法,它允许通过使用像构造函数签名中的参数这样的访问修饰符public或private在构造函数签名中创建所谓的参数属性来更轻松地编写构造函数:
class MyClass {
// body of constructor is not necessary
constructor(public numProperty: number, public strProperty: string) {}
}
let myClassInstance = new MyClass(100, 'hello');
Run Code Online (Sandbox Code Playgroud)
这或多或少与原始代码相同MyClass(我猜参数名称不同),但它减少了样板代码。
这有帮助吗?祝你好运。
| 归档时间: |
|
| 查看次数: |
10030 次 |
| 最近记录: |