Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to selectively inherit interface from another

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 []

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

TS Playground

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]
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading