Jiho
Jiho

Reputation: 348

Angular) Any better way to initialize the value of the Object in class when declaration?

What I'm trying to do is like this.

export class TestModel {
    item1: {title: 'specific title', content: string};
    item2: {title: 'specific title', content: string};
}

declare the object {title:string, value:string}, and initialize only title.
value of the content will be added after it declared.

but It didn't worked. so I changed it to like this.

interface testInterface {
    title: string;
    content: string;
}

export class TestModel {
    item1: testInterface ;
    item2: testInterface ;

    constructor() {
        this.item1 = { title: 'specific titleA', content: '' };
        this.item2 = { title: 'specific titleB', content: '' };
    }
}

I want to initialize title without the constructor(), to reduce the amount of code.
(and if it is possible, initialize only the title, not the content).

I tried
item1: testInterface = { title = 'specific titleA, content = '' };
and it didn't worked too.

Is there any good solution?

Upvotes: 0

Views: 131

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97382

You can assign default values in your field declarations, and then pass Partial objects to the constructor and merge them:

interface TestInterface {
  title: string;
  content: string;
}

export class TestModel {
  item1: TestInterface = {title: 'Default title', content: 'Default content'};
  item2: TestInterface = {title: 'Default title', content: 'Default content'};

  constructor(item1: Partial<TestInterface>, item2: Partial<TestInterface>) {
    this.item1 = {...this.item1, ...item1};
    this.item2 = {...this.item2, ...item2};
  }
}

const x = new TestModel({title: 'Specific title 1'}, {content: 'Content 2'});

If that is still too much repetition, you can declare a constant to hold the default values:

const DEFAULT_TEST_INTERFACE = {title: 'Default title', content: 'Default content'};

export class TestModel {
  item1: TestInterface = DEFAULT_TEST_INTERFACE;
  item2: TestInterface = DEFAULT_TEST_INTERFACE;

  /* rest is same as above */
}

Upvotes: 1

Related Questions