Home > Blockchain >  what will be the type of class object where the class implements an interface and also has it own ne
what will be the type of class object where the class implements an interface and also has it own ne

Time:12-11

I am new to OOP and typescript so here is the sample code

interface Company{
 compName:string;
 compId: number;
 compAdree:string;
}

class Employee implements Company{
 compName="fb";
 compId=83487;
 compAdree="NY";
 emp_name="peter";
 emp_id=99348493;
 emp_adr="Ny"
}

so in above code class Employee is implementing interface company the class has some new members which are not in the interface so if i create a object of the class Employee what will be the type of the object ?

I have came across some code where it is the class type and in some it is the interface type. So i am confused which to use

will it be

let emp:Employee = new Employee()

or will it be

let emp:Company = new Employee()

CodePudding user response:

You can treat Company as a super type and Employee as a sub type. It means that Employee is assignable to Company. Consider this example:

interface Company {
  compName: string;
  compId: number;
  compAdree: string;
}

class Employee implements Company {
  compName: "fb";
  compId: 83487;
  compAdree: "NY";
  emp_name: "peter";
  emp_id: 99348493;
  emp_adr: "Ny"
}

declare let company: Company;
declare let employee: Employee;

company = employee // ok

but not vice versa:

employee=company // error

Let's go back to the original example. This line:

let emp:Employee = new Employee()
emp.compName // ok
emp.emp_adr // ok

means that emp is allowed to use all properties from Company and Employee, whereas this line:

let comp: Company = new Employee()
comp.compName // ok
comp.emp_adr // error

means that comp is allowed to use only Company properties despite the fact that it also contains Employee proper in runtime. It is like static restriction.

Please see Type Compatibility.

Also you probably might have noticed that Employee is a class and it is used both in runtime and type scope. This is a special property of typescript classes and enums. They both might be used in both scopes.

  • Related