[英]How initialize array in typescript?
I'm using InMemoryDbService
in Angular app. 我在Angular应用中使用
InMemoryDbService
。 Some field of model
is custom type. model
某些字段是自定义类型。
The following field is array of classes: 以下字段是类的数组:
public FlightQuotes: CFlightClassQuote[];
The following is initialization of this field: 以下是该字段的初始化:
const cf = new Array<CFlightClassQuote>();
cf[0] = new CFlightClassQuote();
cf[0].Class = 'A';
cf[0].ClassName = 'B';
cf[0].FreeBack = 2;
cf[0].FreeDirect = 5;
cf[1] = new CFlightClassQuote();
cf[1].Class = 'C';
cf[1].ClassName = 'D';
cf[1].FreeBack = 3;
cf[1].FreeDirect = 6;
......
......
const model = new MyModel();
model.FlightQuotes = cf;
Before asking this question i was search but without result. 在问这个问题之前,我正在搜索,但没有结果。 I'm not familiar with typescript syntax.
我对打字稿语法不熟悉。 Can i write shortly initialization of this array?
我可以很快写这个数组的初始化吗? Maybe something like in this:
也许像这样:
model.FlightQuotes = [new CFlightClassQuote{Class = 'A'}, new CFlightClassQuote {Class = 'B'}];
TypeScript doesn't have the style of initialization you have shown in your question (ie the C# style initializer). TypeScript不具有您在问题中显示的初始化样式(即C#样式初始化器)。
You can either create a new one using a constructor: 您可以使用构造函数创建一个新的:
model.FlightQuotes = [
new CFlightClassQuote('A'),
new CFlightClassQuote('B')
];
Or if CFlightClassQuote
is just a structure with no behaviour you can use the below (you have to supply all members) - this won't work if your class has methods etc, but works for interfaces / structures: 或者,如果
CFlightClassQuote
只是没有行为的结构,则可以使用以下内容(您必须提供所有成员)-如果您的类具有方法等,则此方法将无效,但适用于接口/结构:
model.FlightQuotes = [
{ Class: 'A' },
{ Class: 'B' },
];
Or you could create a static mapper method that takes in the members, creates a new instance, and maps the properties - so at least you don't have to repeat that mapping: 或者,您可以创建一个静态的mapper方法,该方法接受成员,创建新实例并映射属性-因此至少您不必重复该映射:
model.FlightQuotes = [
CFlightClassQuote.FromObject({ Class: 'A' }),
CFlightClassQuote.FromObject({ Class: 'B' }),
];
For short initialisation of an array filled with typed objects you can use Object.assign
: 对于填充有类型对象的数组的简短初始化,可以使用
Object.assign
:
model.FlightQuotes = [
Object.assign(new CFlightClassQuote(), {
'Class': 'A',
ClassName: 'B'
}),
Object.assign(new CFlightClassQuote(), {
'Class': 'C',
ClassName: 'D'
}),
];
An other solution: 另一个解决方案:
model.FlightQuotes = [{
Class: 'A',
ClassName: 'B'
} as CFlightClassQuote,
{
Class: 'C',
ClassName: 'D'
} as CFlightClassQuote),
];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.