此Typescript类与此接口如何兼容

时间:2019-02-27 12:37:29

标签: javascript typescript

我是打字稿(和OOP)的新手。我在他们的官方文档中找到了以下示例:

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);

根据我的看法,class Student不具有属性lastname,因此在调用interface Person时应该与function greeter不兼容。

我在这里想念什么?

1 个答案:

答案 0 :(得分:2)

该类确实具有字段lastNamepublic lastName: string是速记字段声明。这既是public字段又是参数声明。这就是构造函数参数中修饰符的含义。有关更多信息,请参见docs