Sign in

After the subclass of typescript inherits the parent class, the subclass object is assigned to the parent class, and no error is reported?

fbit edited in Tue, 19 Jul 2022

Why doesn't an error be reported when a subclass object is assigned to a parent class? Why, what principle?? Help class a {A: string;} class B extends a {B: string;

}class c extends b { c: String;

}let p1: a;let p2: b;let p3: c;p2 = { 'a': 'String', 'b': 'String' }p3 = { 'a': 'String', 'b': 'String', 'c': 'String' }// p1 = p2p2 = p3 console.log (p1,p2,p3)

2 Replies
commented on Wed, 20 Jul 2022

Take a look at document type compatibility in this chapter

interface Named {
    name: string;

let x: Named;
// y's inferred type is { name: string; location: string; }
let y = { name: 'Alice', location: 'Seattle' };
x = y;

Here, we need to check whether y can be assigned to X. the compiler checks every attribute in X to see if the corresponding attribute can also be found in y. In this case, y must contain a string type member whose name is name. Y satisfies the condition, so the assignment is correct.

console.log(x.name) // 正确
console.log(x.location) // 报错提醒

When you use location in X, typescript will give you an error alert

commented on Wed, 20 Jul 2022

Of course, assigning a subclass instance to a parent class reference will not report an error. Not only typescript, but all OOP allow this, such as Java, C #, C + +. On the contrary, if an instance of a parent class is assigned to a reference of a child class, an error will be reported.

The principle is that the inheritance syntax of OOP has such a meaning: the instance of a subclass is also a legal instance of the parent class. Since the instance of a subclass is also an instance of the parent class, why can't it be assigned to the variable of the parent class? Certainly.