I know how to extend a TypeScript interface, but what I'm asking here is how to override a particular key in an interface. For example, say I have a simple interface A
:
interface A {
foo: string;
bar: number;
}
And I have another simple interface B
, also with a bar
key, but of a different type:
interface B {
bar: string;
baz: number;
}
Essentially, I want to merge these interfaces into one, giving me the following interface:
interface C {
foo: string; // from A.foo
bar: string; // from B.bar (overrides A.bar)
baz: number; // from B.baz
}
I wish I could just extend somehow:
interface C extends A, B {}
But I can't, because I get this error, which is totally expected and by design:
Interface 'C' cannot simultaneously extend types 'A' and 'B'. Named property 'bar' of types 'A' and 'B' are not identical.
I'm just not sure if there's another mechanism of which I am unaware. I don't think intersection or union types help here either.
A little late... but I fixed this issue creating another type...
type ExcludeAddress<T> = Omit<T, 'addresses'>;
This type excludes a specific key (I called 'address') from the interface...
I used it to solve a problem where I needed to cast a value of the interface...
I removed it and then created a new interface extending the old interface(without the key) + an interface with the new keyType...
Example:
type ExcludeAddress<T> = Omit<T, 'addresses'>;
export interface IAvailability {
readonly frequency: number;
readonly duration: number;
readonly date: string;
readonly addresses: Address[];
}
export interface ISerializedAvailability extends ExcludeAddress<IAvailability> {
readonly addresses: string[];
}
You would need to adjust the ExcludeAddress I created for you own personal project...
Maybe it's not cleaneast solution, but well... it works
In my example: I created ISerializedAvailability is essencially an IAvailability where address has type string[] and not Address[]