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} };
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}};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With