2

Consider the following interfaces :

interface MyType1 {
  field1: string;
    options: {
        basicOption1: string;
        basicOption2: string; 
    };
}

interface MoreOptions {
    moreOptions1: string;
    moreOptions2: string;
}

I extend the field options of interface MyType1 :

interface MyType2 extends MyType1{
    options: {
        basicOption1: string; // How to remove it, yet declared in MyType1
        basicOption2: string; // How to remove it, yet declared in MyType1
        moreOptions1: string;
        moreOptions2: string; 
    };
}

If I omit lines : basicOptions1:string;and basicOptions2:string;, compiler complains. So, I add them. But, is it possible to remove them and only keep lines : moreOptions1:string; and moreOptions2:string; for the additional options.

Following, how could I assign an object of type Mytype2 from two objects of type MyType1 and MoreOptions ?

For example (Rq : I test other things but also unsuccessful) :

let myobj1: MyType1 = { field1:"field1", options:{ basicOption1:"basicOption1", basicOption2:"basicOption2" } };
let moreOptions: MoreOptions = { moreOptions1: "moreOptions1", moreOptions2: "moreOptions2" }

let myobj2: MyType2 = { ...myobj1, options: {...moreOptions} };

1 Answer 1

8

You can intersect the desired types for options property:

interface MyType2 extends MyType1 {
    options: MyType1["options"] & MoreOptions
}

Concerning MyType2 extends MyType1 and the error:

Existing properties in MyType1 like options have to be identical in MyType2, they do not get overwritten or merged in somehow. Other properties like field1 are automatically carried over.


Following, how could I assign an object of type Mytype2 from two objects of type MyType1 and MoreOptions ?

You can use object spread, which will merge all objects and in case of equally named properties choose the right-most one (Playground sample):

declare const t1: MyType1;
declare const moreOpt: MoreOptions;
const t2: MyType2 = {...t1, options: {...t1.options, ...moreOpt}};
Sign up to request clarification or add additional context in comments.

2 Comments

Concerning the second question, is there a mean to add moreOptions to myobj2 ? When I read your answer, it seems that it is not possible.
Thanks a lot, you give me a simple idea !!! It works. let myobj2: MyType2 = { ...myobj1, options: {...myobj1.options, ...moreOptions} }; Could you complete your answer an after I will accept it.

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.