1

I am creating a person interface and created a method greeter that takes in a person and prints its first and last name. Then I created a class student with a firstname and last name. Created an object of student and passed to greeter function and it works.

class Student{
    fullName: string;
    constructor(public firstName: string, public middleName: string ,public lastName: string)
    {
        this.fullName=firstName+" "+ middleName+" "+lastName;
    }
}
interface Person {
    firstName: string;
    lastName: string;
}

function greeter(person: Person) {
    return "Hello, " + person.firstName + " " + person.lastName;
}
let user =new Student("jane","doe","user");
document.body.textContent = greeter(user);

It should give an error

expected a person but got a student

but actually it prints fine.

Dale K
  • 25,246
  • 15
  • 42
  • 71

1 Answers1

0

The reason you're not getting an error is that your Student class is implicitly declaring firstName, middleName, and lastName properties through your use of the public keyword. In fact, any modifiers on constructor parameters result in automatic declaration and initialization of the corresponding member. As a result, Student is directly assignable to Person.

IMO this is a confusing construct to those not super familiar with the language, and I personally prefer to be explicit. If you're using TSLint, you can disallow this syntax using no-parameter-properties.

If you want to keep those properties as is but make sure that Student is not assignable to Person, you'll need to add another property to Person to make it incompatible, i.e., isPerson: true;.

Oleg Vaskevich
  • 12,444
  • 6
  • 63
  • 80