2016-02-11 55 views
1

是否可以使用不同的特定实现内联初始化接口类型为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" 
     } 
    }; 
} 

这是我在打字稿尝试:

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" 
    // }  
]; 

回答

1

没有,打字稿does not have object initializers。 @RyanCavanaugh显示possible solution在TS:

class MyClass { 
    constructor(initializers: ...) { ... } 
} 

var x = new MyClass({field1: 'asd', 'field2: 'fgh' }); 
+0

哇...我甚至没有意识到,没有任何对象初始化在所有 - 我一直以为它工作时,你只是做'VAR BLA:富{。 ..''但是如果你用'instance of'查看它甚至不是'Foo'的实例,而不是'object' ......我必须说我有点失望......无论如何。 –