TypeScript 和字段初始值设定项 [英] TypeScript and field initializers

查看:33
本文介绍了TypeScript 和字段初始值设定项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以这种方式在 TS 中初始化一个新类(C# 中的示例以显示我想要的内容):

How to init a new class in TS in such a way (example in C# to show what I want):

// ... some code before
return new MyClass { Field1 = "ASD", Field2 = "QWE" };
// ...  some code after

推荐答案

更新

自从写下这个答案以来,出现了更好的方法.请参阅下面有更多投票和更好答案的其他答案.我无法删除此答案,因为它已标记为已接受.

Update

Since writing this answer, better ways have come up. Please see the other answers below that have more votes and a better answer. I cannot remove this answer since it's marked as accepted.

TypeScript codeplex 有一个问题描述了这一点:支持对象初始值设定项.

There is an issue on the TypeScript codeplex that describes this: Support for object initializers.

如前所述,您已经可以通过在 TypeScript 中使用接口而不是类来做到这一点:

As stated, you can already do this by using interfaces in TypeScript instead of classes:

interface Name {
    givenName: string;
    surname: string;
}
class Person {
    name: Name;
    age: number;
}

var bob: Person = {
    name: {
        givenName: "Bob",
        surname: "Smith",
    },
    age: 35,
};

这篇关于TypeScript 和字段初始值设定项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆