简体   繁体   中英

How is this Typescript class compatible with this interface

I am new to typescript(and OOP). I found the following example in their official documentation:

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

interface Person {
    firstName: string;
    lastName: string;
}

function greeter(person : Person) {
    return "Hello, " + person.firstName + " " + person.lastName;
}

let user = new Student("Jane", "M.", "User");

document.body.innerHTML = greeter(user);

The way I see it, class Student doesn't have the property lastname and thus shouldn't be compatible with the interface Person when the function greeter is being called.

What am I missing here?

The class does have a field lastName . public lastName: string is a shorthand field declaration. This is both a public field and a parameter declaration. That is the meaning of the modifier in the constructor parameter. See the docs for more information

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM