如何以TS这种方式初始化新类(示例C#以显示我想要的内容):
// ... some code before
return new MyClass { Field1 = "ASD", Field2 = "QWE" };
// ... some code after
[edit]
当我写这个问题时,我是一个纯粹的.NET开发人员,没有太多的JS知识。TypeScript也是全新的东西,它是基于C#的JavaScript的超集。今天,我看到这个问题多么愚蠢。
无论如何,如果有人仍在寻找答案,请查看以下可能的解决方案。
首先要注意的是在TS中,我们不应为模型创建空类。更好的方法是创建接口或类型(取决于需求)。来自Todd Motto的好文章:https : //ultimatecourses.com/blog/classes-vs-interfaces-in-typescript
解决方案1:
type MyType = { prop1: string, prop2: string };
return <MyType> { prop1: '', prop2: '' };
解决方案2:
type MyType = { prop1: string, prop2: string };
return { prop1: '', prop2: '' } as MyType;
解决方案3(当您确实需要上课时):
class MyClass {
constructor(public data: { prop1: string, prop2: string }) {}
}
// ...
return new MyClass({ prop1: '', prop2: '' });
要么
class MyClass {
constructor(public prop1: string, public prop2: string) {}
}
// ...
return new MyClass('', '');
当然,在两种情况下,您可能都不需要手动转换类型,因为它们将从函数/方法返回类型中解析。
return new MyClass { Field1: "ASD", Field2: "QWE" };