Can I inherit one interface into another in typescript? How can I access the property defined in the inherited interface?

Viewed 34755

Two interface are there first one is ICat and second one is IMammal. IMammal extends ICat. Will the Cat property in IMammal have the capability to access all the property of ICat interface?

export interface ICat {
    Cateye: string[];
    Color: string;    
    Name: string;
}

export interface IMammal extends ICat {
    Description: string;
    HasImage: boolean;   
    CatGroup: string[];
    **Cat: ICat[]**;
}

Basically, how can I achieve multiple interface inheritances in Typescript?

2 Answers

I think maybe ICat should extend IMammal because Cat is a Mammal, and a Mammal do not need any references to ICat, think if you want to add IDog one day:

export interface IMammal {
    Description: string;
    HasImage: boolean;   
}

export interface ICat extends IMammal {
    Cateye: string[];
    CatGroup: string[];
    Color: string;    
    Name: string;
}

class Cat implements ICat {
    Cateye: string[];
    Color: string;    
    Name: string;
    Description: string;
    HasImage: boolean;   
    CatGroup: string[];
 }

const pusur:ICat = new Cat();
pusur.Name = "Pusur";
pusur.Description = "Likes lasagna";
pusur.CatGroup = ["Cartoon cat"];

You use implements for interfaces, use extends for class inheritance. implements allows you to pass a list of interfaces which are implemented by the class.

Note that quite often it won't matter, as a class that implements all of the properties and methods of an interface is automatically compatible with the interface whether or not it explicitly implements the interface, but listing the interfaces explicitly at least means the compiler will tell you if you failed to implement them correctly.

interface A {
    a: string;
}

interface B {
    b: string;
}

class Foo implements A,B {
  a: string;
  b: string;
}

function foo(b: B) {}
function bar(a: A) {}

const f = new Foo();
foo(f);
bar(f);
Related