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' });