user6408649
user6408649

Reputation: 1305

How initialize array in typescript?

I'm using InMemoryDbService in Angular app. Some field of model is custom type.

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

Upvotes: 0

Views: 1480

Answers (3)

ArDumez
ArDumez

Reputation: 1001

An other solution:

model.FlightQuotes = [{
        Class: 'A',
        ClassName: 'B'
    } as CFlightClassQuote,    
    {
        Class: 'C',
        ClassName: 'D'
    } as CFlightClassQuote),
];

Upvotes: 0

Poul Kruijt
Poul Kruijt

Reputation: 71911

For short initialisation of an array filled with typed objects you can use Object.assign:

model.FlightQuotes = [
    Object.assign(new CFlightClassQuote(), {
        'Class': 'A',
        ClassName: 'B'
    }),    
    Object.assign(new CFlightClassQuote(), {
        'Class': 'C',
        ClassName: 'D'
    }),
];

Upvotes: 1

Fenton
Fenton

Reputation: 250922

TypeScript doesn't have the style of initialization you have shown in your question (i.e. the C# style initializer).

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:

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:

model.FlightQuotes = [
    CFlightClassQuote.FromObject({ Class: 'A' }),
    CFlightClassQuote.FromObject({ Class: 'B' }),
 ];

Upvotes: 1

Related Questions