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
Add a ment  | 

3 Answers 3

Reset to default 13

The 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