是否可以使用不同的特定实现内联初始化接口类型IFooFace
的数组?或者它是不可能的,我必须在数组之前初始化我的对象,然后只是传入它们?
这就是我在C#中的表现方式:
public interface IFooFace
{
int Id { get; }
}
public class Bar : IFooFace
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Zar : IFooFace
{
public int Id { get; set; }
public string MegaName { get; set; }
}
internal class Program
{
public static IFooFace[] Data =
{
new Bar
{
Id = 0,
Name = "first"
},
new Zar
{
Id = 1,
MegaName = "meeeega"
}
};
}
这就是我在TypeScript中尝试过的:
export interface IFooFace {
id: number;
}
export class Bar implements IFooFace {
public id: number;
public name: string;
// a lot of more properties
}
export class Zar implements IFooFace {
public id: number;
public megaName: string;
// a lot of more properties
}
var Data : IFooFace[] = [
// how to initialize my objects here? like in C#?
// this won't work:
// new Bar(){
// id: 0,
// name: "first"
// },
// new Zar() {
// id: 1,
// megaName: "meeeeega"
// }
// this also doesn't work:
// {
// id: 0,
// name: "first"
// },
// {
// id: 1,
// megaName: "meeeeega"
// }
];
答案 0 :(得分:1)
不,TypeScript does not have object initializers。 @RyanCavanaugh在TS中显示possible solution:
class MyClass {
constructor(initializers: ...) { ... }
}
var x = new MyClass({field1: 'asd', 'field2: 'fgh' });