Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Interface 在接口类型的数组中内联初始化不同类型的对象_Interface_Typescript_Initialization - Fatal编程技术网

Interface 在接口类型的数组中内联初始化不同类型的对象

Interface 在接口类型的数组中内联初始化不同类型的对象,interface,typescript,initialization,Interface,Typescript,Initialization,是否可以使用不同的特定实现内联初始化接口类型IFooFace的数组?还是不可能,我必须在数组之前初始化我的对象,然后将它们传入 这就是我在C#中可以做到的: 这就是我在TypeScript中尝试的: export interface IFooFace { id: number; } export class Bar implements IFooFace { public id: number; public name: string; // a lot o

是否可以使用不同的特定实现内联初始化接口类型
IFooFace
的数组?还是不可能,我必须在数组之前初始化我的对象,然后将它们传入

这就是我在C#中可以做到的:

这就是我在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"
    // }    
]; 
不,打字稿@RyanCavanaugh在TS中显示:


哇!我甚至没有意识到根本没有任何对象初始值设定项-我一直认为当你只做
var bla:Foo{…}
时它是有效的,但是如果你稍后查看
实例,它甚至不是
Foo
的实例,而是
对象
…我必须说我有点失望。。。无论如何,谢谢你。
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"
    // }    
]; 
class MyClass {
  constructor(initializers: ...) { ... }
}

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