0

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

3 Answers 3

1

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'
    }),
];
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

An other solution:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.