0

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?

0

1 Answer 1

1

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 */
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow. Thanks! I didn't know the Partial Object.

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.