Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do Typescript classes implement interfaces automatically?

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);
like image 571
AdHominem Avatar asked Aug 26 '26 11:08

AdHominem


1 Answers

This is called Structural Typing. Essentially, relationships between types in TypeScript are never required to be explicitly declared ('named', as in nominal typing, like C#, Java and friends), they're done purely by analysing the structure of the types involved.

In TypeScript when you say that a class implements an interface, you're not actually changing the class at all, or the types of the subclasses involved, you're just asking the compiler to confirm that it does indeed already implement that interface.

As for the reasoning, the key factor here (as with many decisions in TypeScript) is that this more closely matches what JavaScript does in practice (i.e. duck typing - if you pass something the right shape, it'll work), so makes compatibility with existing JavaScript code far easier.

Notably this does leave TypeScript with some limitations. For example, you can't use identical but incompatible types as marker interfaces to limit input, as in Java. In Java Serializable and Cloneable cloneable are two empty interfaces which can be implemented to mark a type as serializable or cloneable, and methods can then accept only Serializable parameters to ensure they get only classes which are explicitly known to be safe to serialize. In TypeScript, you can't do that: an empty interface doesn't change the structure of an object, so doesn't make any difference to the type system at all.

like image 57
Tim Perry Avatar answered Aug 29 '26 17:08

Tim Perry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!