In typescript, the following compiles.
class Person {
name : string;
}
class Employee {
name : string;
}
var person : Person = new Employee();
Why does that work?? This does not:
class Person {
name : string;
surname : string;
}
class Employee {
name : string;
}
var person : Person = new Employee();
With the exception that:
Type employee is not assignable to type Person, the property surname is missing in type Employee
So. Types are compared at compile time using property names??!
Edit: Yep. This is the code from the typescript compiler doing the checking.
for (var i = 0; i < targets.length; i++) {
var related = isRelatedTo(sources[i], targets[i], reportErrors);
if (!related) {
return 0;
}
result &= related;
}
return result;
[...]Type compatibility in TypeScript is based on structural subtyping. Structural typing is a way of relating types based solely on their members. This is in contrast with nominal typing.[...]