我创建了一个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是所有constructor
函数的要求。#2只是一个快捷方式,使您的工作更轻松,只有当您在变量之前使用public
这样的修饰符时才会出现。
当你声明class Admin extends User
时,Admin
继承了#2的所有类型。它知道Admin
实例必须有name
和employees
。不从#1继承类型
Admin
constructor
的唯一规则是它必须带参数(string, string[])
调用super(name, employees)
。它不需要遵循与User
构造函数相同的格式。它可以接受不同顺序的参数,使用任意数量的任意类型的参数来派生name
和employees
,甚至可以接受零参数并使用一些预定义的常量调用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
}
最后一个(这是你永远不应该写的可怕的代码)是为了证明你可以有相同的变量name
和employees
,与User
构造函数的顺序相同,而不是共享相同的类型。这就是为什么#1类型不能被继承。
总结:
据我所知,super()调用USer的构造函数,所以所有属性都继承到子类。
正确。
为什么我需要在ADmin类中再次声明属性的类型?该类型不应该转移到ADmin吗?
您没有声明属性的类型。您正在为constructor
函数声明函数参数的类型。