Is it possible to selectively inherit interface from another
See examples below
interface A {
id: string
name: string
gender:string
address: string []
}
interface B {
id: string
name: string
gender:string
address: number []
}
The only difference is the attribute address , one is string [] and another one is number []
Can I do this ?
interface B extend A {
address: number []
}
>Solution :
Well no you can’t, you will get an error:
Interface 'B' incorrectly extends interface 'A'.
Types of property 'address' are incompatible.
Type 'number[]' is not assignable to type 'string[]'.
Type 'number' is not assignable to type 'string'.
But what you can do is inherit all the fields except address using Omit
interface A {
id: string;
name: string;
gender: string;
address: string[];
}
// This doesn't work
/*
interface B extends A {
address: number[];
}
*/
// This does
interface B2 extends Omit<A,"address"> {
address: number[];
}
const myInstance: B2 = {
id: "1",
name: "Foo",
gender: "male",
address: [1, 2, 3]
};
Another valid solution would be to have a generic interface.
interface X<T = number | string> {
id: string;
name: string;
gender: string;
address: T[];
}
interface A extends X<string> {
}
interface B extends X<number> {
}
const instance: B = {
id: "1",
name: "Foo",
gender: "male",
address: [1, 2, 3]
};