So I did the Typescript tutorial without any former JS experience. My question is in given example code, why can you pass the Student object into the greeter() function which takes a Person as parameter? The class Student never implements said interface so I wonder if in Typescript classes automatically implement interfaces. And if they do, what's the reasoning behind this? It seems pretty useless if Car, Plane and Student all automatically implement Person.
class Student {
fullName: string;
constructor(public firstName, public middleInitial, public lastName) {
this.fullName = firstName + " " + middleInitial + " " + lastName;
}
}
interface Person {
firstName: string;
lastName: string;
}
function greeter(person : Person) {
return "Hello, " + person.firstName + " " + person.lastName;
}
var user = new Student("Jane", "M.", "User");
document.body.innerHTML = greeter(user);
Personif it hasfirstNameandlastNameproperties of typestring. - Leepublickeywords in front of the parameter names turns them into fields. The lack of type annotation means they're of typeany; fields of typeanyare compatible with any other type. - Ryan Cavanaugh