如何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
当前回答
这是如何……
function as_<T>(o: T) { return o; };
// ... some code before
return as_<MyClass>({ Field1 = "ASD", Field2 = "QWE" });
// ... some code after
其他回答
可以影响类类型中强制转换的匿名对象。 奖励:在visual studio中,你可以这样受益于智能感知:)
var anInstance: AClass = <AClass> {
Property1: "Value",
Property2: "Value",
PropertyBoolean: true,
PropertyNumber: 1
};
编辑:
警告:如果类有方法,类的实例将得不到它们。如果AClass有构造函数,它将不会被执行。如果使用instanceof AClass,则会得到false。
总之,应该使用接口而不是类。 最常见的用途是声明为普通旧对象的域模型。 实际上,对于域模型,您应该更好地使用接口而不是类。接口在编译时用于类型检查,与类不同,接口在编译期间被完全删除。
interface IModel {
Property1: string;
Property2: string;
PropertyBoolean: boolean;
PropertyNumber: number;
}
var anObject: IModel = {
Property1: "Value",
Property2: "Value",
PropertyBoolean: true,
PropertyNumber: 1
};
这是另一个解决方案:
return {
Field1 : "ASD",
Field2 : "QWE"
} as myClass;
在某些情况下,使用Object.create可能是可以接受的。如果您需要向后兼容或想要滚动自己的初始化函数,Mozilla引用包含一个polyfill。
应用于你的例子:
Object.create(Person.prototype, {
'Field1': { value: 'ASD' },
'Field2': { value: 'QWE' }
});
有用的场景
单元测试 内联声明
在我的案例中,我发现这在单元测试中很有用,原因有二:
在测试期望时,我经常希望创建一个苗条的对象作为期望 单元测试框架(如Jasmine)可能会比较对象原型(__proto__)并使测试失败。例如:
var actual = new MyClass();
actual.field1 = "ASD";
expect({ field1: "ASD" }).toEqual(actual); // fails
单元测试失败的输出不会产生关于不匹配的线索。
在单元测试中,我可以选择我支持的浏览器
最后,http://typescript.codeplex.com/workitem/334上提出的解决方案不支持内联json风格的声明。例如,以下代码不能编译:
var o = {
m: MyClass: { Field1:"ASD" }
};
我更倾向于这样做,使用(可选的)自动属性和默认值。您没有建议这两个字段是数据结构的一部分,所以这就是我选择这种方式的原因。
您可以在类中拥有属性,然后以通常的方式分配它们。显然,他们可能需要,也可能不需要,所以这也是另一回事。只是这是一个很好的语法糖。
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版本
类定义
export class PaymentRequestDto {
public PaymentSource: number;
public PaymentCenterUid: string;
public ConnectedUserUid: string;
}
你有一些来自某处的价值观:
const PaymentCenter= 'EA0AC01E-D34E-493B-92FF-EB2D66512345';
const PaymentSource= 4;
const ConnectedUser= '2AB0D13C-2BBE-46F5-990D-533067BE2EB3';
然后可以在使用强类型时初始化对象。
const parameters: PaymentRequestDto = {
PaymentSource,
PaymentCenterUid: PaymentCenter,
ConnectedUserUid: ConnectedUser,
};
PaymentSource不需要名称字段说明符,因为使用的变量具有与字段相同的名称。
这也适用于数组。
const parameters: PaymentRequestDto [] = [
{
PaymentSource,
PaymentCenterUid: PaymentCenter,
ConnectedUserUid: ConnectedUser,
},
{
. . . .
}
];