我是打字稿(和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
不兼容。
我在这里想念什么?
答案 0 :(得分:2)
该类确实具有字段lastName
。 public lastName: string
是速记字段声明。这既是public
字段又是参数声明。这就是构造函数参数中修饰符的含义。有关更多信息,请参见docs