超和TypeScript中的属性继承



我创建了一个USer类并创建了一个子类ADmin

class USer {
constructor(public name: string, public employees: string[]) {  // wieso dann hier nochmal type zuordnen dachte das wäre das gleiche oder ?
}
login(this: User){   

}

}
class ADmin extends USer {
constructor(name: string, employes: string[], public admin: string){
super(name, employes); // calls the constructor of the USer !
}

}

根据我的理解,super()调用USer的构造函数,所以所有的属性都继承到子类。

如果我不声明属性类型,我得到

Argument of type 'void' is not assignable to parameter of type 'string'

为什么我需要在ADmin类中再次声明属性的类型?

是否应该将该类型转移到ADmin?

构造函数中的类型正在做两件事:

  1. 它们声明传递给构造函数的参数的类型
  2. 它们声明类的实例变量的类型

#1是所有constructor函数的要求。#2只是一个快捷方式,使您的工作更轻松,只有当您在变量之前使用public这样的修饰符时才会出现。

当你声明class Admin extends User时,Admin继承了#2的所有类型。它知道Admin实例必须有nameemployees从#1继承类型

Adminconstructor的唯一规则是它必须带参数(string, string[])调用super(name, employees)。它不需要遵循与User构造函数相同的格式。它可以接受不同顺序的参数,使用任意数量的任意类型的参数来派生nameemployees,甚至可以接受零参数并使用一些预定义的常量调用super

下面是一些愚蠢的构造函数的例子,它们都是有效的
constructor(name: string[]){
super(name[0], []); // derive name, create employees
}
constructor(object: {name: string, employees: string[]}){
super(object.name, object.employees); // derive name & employees
}
constructor(){
super("The Admin", []); // create name & employees
}
constructor(name: string[], employees: string){
super(employees, name); // TERRIBLE code with backwards variables
}

最后一个(这是你永远不应该写的可怕的代码)是为了证明你可以有相同的变量nameemployees,与User构造函数的顺序相同,而不是共享相同的类型。这就是为什么#1类型不能被继承。

总结:

据我所知,super()调用USer的构造函数,所以所有属性都继承到子类。

正确。

为什么我需要在ADmin类中再次声明属性的类型?该类型不应该转移到ADmin吗?

您没有声明属性的类型。您正在为constructor函数声明函数参数的类型。

最新更新