简体   繁体   中英

Typescript type checking mechanism

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;

Effectively, Typescript determines types of objects based on their 'shape' - if two classes have the same members and their types and accessibility match, they're said to be compatible and can be used interchangeably. The same goes for functions. As t.niese mentioned in their comment, you can find more information of the reasoning behind this and the implications in the TypeScript handbook . It basically stems from the fact that JavaScript makes heavy use of anonymous functions and objects, so having a stricter type system may have made using existing JS libraries from within TypeScript an awkward task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM