I have this interface
interface Base {
common: {
foo: string,
}
}
interface ExtendedOne extends Base {
count: number,
}
interface ExtendedTwo extends Base {
origin: string,
}
Now, what I want is via the interface definition of ExtendedOne and ExtendedTwo add another property plus type to the common prop coming from Base.
So lets say (pseudocode)
interface ExtendedOne extends Base {
count: number,
common: {
...Base,
anotherProp: boolean,
}
}
interface ExtendedTwo extends Base {
origin: string,
common: {
...Base,
anotherProp: number,
}
}
The prop added will always have the same name (here anotherProp), but the type will be different.
If needed, the interface can be changed to a type.
>Solution :
You can use & operator in Typescript to combine types.
interface Base {
common: {
foo: string;
};
}
interface ExtendedOne extends Base {
count: number;
common: Base["common"] & { anotherProp: boolean };
}
interface ExtendedTwo extends Base {
origin: string;
common: Base["common"] & { anotherProp: number };
}
TypeScript has some great utility types too. For examples, check Omit and Pick that allow you to selectively create a new type by omitting or picking properties from another type.