Ole Albers Ole Albers - 1 year ago 137
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
(c#) or
Student implements Person
So: Why does
accept an object of class "
"? I did not see any clue that "
" implements "

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

class Teacher {

an object of that class would also be a valid parameter for

Answer Source

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download