admin管理员组文章数量:1278947
class test1
{
testName: string;
testNum: number;
}
class test2 extends test1
{
constructor(conName:string, conNum: number)
{
}
}
but it won't work because it says that "Derived class must implement super"
class test1
{
testName: string;
testNum: number;
}
class test2 extends test1
{
constructor(conName:string, conNum: number)
{
}
}
but it won't work because it says that "Derived class must implement super"
Share Improve this question asked Sep 10, 2018 at 10:18 Jameela KhanJameela Khan 691 silver badge5 bronze badges 4-
Add
super()
to the body of the constructor – Ploppy Commented Sep 10, 2018 at 10:21 - You need to call super() in class2 constructor – mpm Commented Sep 10, 2018 at 10:21
- Possible duplicate of Using TypeScript super() – Ploppy Commented Sep 10, 2018 at 10:23
- great. worked but why would it need that ? If i don't use constructor in test2 then it doesn't also need for test1. Why? – Jameela Khan Commented Sep 10, 2018 at 10:33
3 Answers
Reset to default 13The error you are getting is actually:
Constructors for derived classes must contain a 'super' call
The reason for this is that the base class must be initialized from the derived class by calling the base class constructor (using the super
keyword).
class test1
{
testName: string;
testNum: number;
}
class test2 extends test1
{
constructor(conName:string, conNum: number)
{
super()
}
}
You need to call the parent class constructor explicitely
class test1
{
testName: string;
testNum: number;
}
class test2 extends test1
{
constructor(conName:string, conNum: number)
{
super()
}
}
When you create a class, an empty constructor is automatically created for you. These are equivalent:
// implicit
class test1
{
testName: string;
testNum: number;
}
// explicit
class test1
{
testName: string;
testNum: number;
public constructor() {
}
}
All child must call their parent constructor explicitely with super
Each derived class that contains a constructorfunction must call
super()
which will execute the constructor of the base class. [•••] This is an important rule that TypeScript will enforce.
From the doc
My guess is that this decision maybe a type check performance tradeoff (source needed). By enforcing this rule, typescript does not have to check if the constructor of the base class is indeed empty.
Since you used extends
on test2
which is a child of test1
(more here), you will need to call super()
and pass in anything that belongs in the test1
constructor. However, since there is nothing to pass, just call super()
inside of test2
constructor.
本文标签: javascriptWhy can39t I create a constructor in derived classStack Overflow
版权声明:本文标题:javascript - Why can't I create a constructor in derived class? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741292020a2370605.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论