Ole Albers Ole Albers - 4 months ago 13
TypeScript Question

classes and Interfaces in Typescript

I am in the beginning of learning TypeScript. I come from a strongly-typed language (c#) and have some knowledge in JS.

Quite at the beginning I fell over the following example:

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


Now I am a bit confused. I would expect something like
Student:Person
(c#) or
Student implements Person
(Java)
So: Why does
greeter()
accept an object of class "
Student
"? I did not see any clue that "
Student
" implements "
Person
".

is it just about the property names?
So if I add another class

class Teacher {
salaray:int,
firstName:string,
lastName:string
}


an object of that class would also be a valid parameter for
greeter()
?

Answer

Yes you are right about your assumption. You can see the code that typescript transpiles into. The code that you posted (I changed the last line to an alert) looks like this

var Student = (function () {
    function Student(firstName, middleInitial, lastName) {
        this.firstName = firstName;
        this.middleInitial = middleInitial;
        this.lastName = lastName;
        this.fullName = firstName + " " + middleInitial + " " + lastName;
    }
    return Student;
}());

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

var user = new Student("Jane", "M.", "User");
alert(greeter(user));

Once the typescript is transpiled to javascript, all that knowledge of those interfaces and classes is lost. You can see that from the transpiled example above. In this example, it makes sense that it would run correctly because the incoming variable person actually does have the properties that the method is accessing. So Typescript can see that the transpiled version of your code actually does make sense and will not complain about it.