I am new to typescript and came across classes which implement interface. I know that a class can add properties that the interface didn't have, but it must contain all the properties the interface has. My problem is when i am making a new object from my class with a type of a certain interface, it gets confusing. I saw on the site of tutorial teachers, the following code
interface IPerson {
name: string;
display():void;
}
interface IEmployee {
empCode: number;
}
class Employee implements IPerson, IEmployee {
empCode: number;
name: string;
constructor(empcode: number, name:string) {
this.empCode = empcode;
this.name = name;
}
display(): void {
console.log("Name = " + this.name + ", Employee Code = " + this.empCode);
}
}
let per:IPerson = new Employee(100, "Bill");
per.display(); // Name = Bill, Employee Code = 100
let emp:IEmployee = new Employee(100, "Bill");
emp.display(); //Compiler Error: Property 'display' does not exist on type IEmployee'
If after let per:IPerson = new Employee(100, "Bill"); i would console.log(per.empCode) there will be a compiler error saying
Property 'empCode' does not exist on type 'IPerson'.
So why does per.display() manage to log the empCode even when the type is Iperson amd that does not have a empCode Property. Please can you help me understand the difference