简体   繁体   中英

How Typescript allowed calling function with different parameter types?

"typescript": "2.7.2"

How/WHY this code worked without any IDE error or --aot compile error on Angular 6 project?

private func1() {
    const b: B = new B();
    b.name = 'jack';
    this.func2(b);
}

private func2(a: A) {
    console.log(a.name); //prints jack
}

-

export class A {
    public name: string;
}

export class B {
    public name: string;
    public surname: string;
}

TypeScript uses a structural type system. This means that types are compared by their contents . As opposed to most other everyday languages, who use nominal type systems where types are compared by their name . Therefore, in TypeScript, your type B can be used where type A is expected because the "shape" of type B exactly matches the "shape" needed for type A – all the members of type A are present in type B and their own types match.

This approach was selected by the TypeScript language designers because it fits well with existing JavaScript idioms, such as using plain object literals received via AJAX without coercing them into a named type. This design choice causes some friction in scenarios when nominal type system elements would be convenient (eg identifier types like ProductId and OrderId should be incompatible).

Relevant reading:

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