如何init一个新的类在TS以这样的方式(在c#的例子,以显示我想要的):
// ... some code before
return new MyClass { Field1 = "ASD", Field2 = "QWE" };
// ... some code after
如何init一个新的类在TS以这样的方式(在c#的例子,以显示我想要的):
// ... some code before
return new MyClass { Field1 = "ASD", Field2 = "QWE" };
// ... some code after
当前回答
如果你使用的是旧版本的typescript < 2.1,那么你可以使用类似于下面的方法,基本上是将任意类型转换为类型化对象:
const typedProduct = <Product>{
code: <string>product.sku
};
注意:使用此方法只适用于数据模型,因为它将删除 对象中的所有方法。它基本上是将任何对象转换为a 类型的对象
其他回答
更新
写完这个答案后,更好的方法出现了。请看下面的其他答案,有更多的投票和更好的答案。我不能删除这个答案,因为它被标记为已接受。
旧的答案
TypeScript codeplex上有一个问题描述了这一点:支持对象初始化器。
如前所述,你已经可以通过在TypeScript中使用接口而不是类来做到这一点:
interface Name {
givenName: string;
surname: string;
}
class Person {
name: Name;
age: number;
}
var bob: Person = {
name: {
givenName: "Bob",
surname: "Smith",
},
age: 35,
};
最简单的方法是使用类型强制转换。
return <MyClass>{ Field1: "ASD", Field2: "QWE" };
我更倾向于这样做,使用(可选的)自动属性和默认值。您没有建议这两个字段是数据结构的一部分,所以这就是我选择这种方式的原因。
您可以在类中拥有属性,然后以通常的方式分配它们。显然,他们可能需要,也可能不需要,所以这也是另一回事。只是这是一个很好的语法糖。
class MyClass{
constructor(public Field1:string = "", public Field2:string = "")
{
// other constructor stuff
}
}
var myClass = new MyClass("ASD", "QWE");
alert(myClass.Field1); // voila! statement completion on these properties
我建议一种不需要Typescript 2.1的方法:
class Person {
public name: string;
public address?: string;
public age: number;
public constructor(init:Person) {
Object.assign(this, init);
}
public someFunc() {
// todo
}
}
let person = new Person(<Person>{ age:20, name:"John" });
person.someFunc();
重点:
Typescript 2.1不需要,Partial<T>不需要 它支持函数(与不支持函数的简单类型断言相比)
如果要创建新实例时没有设置初始值
1-你必须使用类而不是接口
2-你必须在创建类时设置初始值
export class IStudentDTO {
Id: number = 0;
Name: string = '';
student: IStudentDTO = new IStudentDTO();