0

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

1 Answer 1

1

This is standard behavior in an object oriented programming language. Basically when you do:

let per:IPerson = new Employee(100, "Bill");

The compiler only cares about the type of per which is IPerson. IPerson does not have the property empCode. Even though we know it is an Employee and this does have a empCode property the compiler can not know this for certain!

When you do per.display() the empCode is accessible because at that point you will be inside the scope of the Employee class.

Sign up to request clarification or add additional context in comments.

2 Comments

Agree to the answer. Another suggestion could be using the addition of IPerson + IEmployee. i.e: interface IPersonEmployee { name: string; display():void; empCode: number; } ..... let per:IPersonEmployee = new IPersonEmployee(100,'Bill', 200);
@AlbertoAM don't created a 'merged' interface by redefining the properties again. Simply do: interface IPersonEmployee extends IPerson, IEmployee {}. Also your code sample is broken: you cannot instantiate an interface as you are doing here. That's a basic property of interfaces.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.