Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you access properties of base class in Typescript?

Tags:

There was a suggestion of using code like this

class A {
    // Setting this to private will cause class B to have a compile error
    public x: string = 'a';
}

class B extends A {
    constructor(){super();}
    method():string {
        return super.x;
    }
}

var b:B = new B();
alert(b.method());

and it even got 9 votes. But when you paste it on the official TS playground http://www.typescriptlang.org/Playground/ it gives you and error.

How to access the x property of A from B?

like image 225
Alex Vaghin Avatar asked Oct 10 '13 04:10

Alex Vaghin


People also ask

Which keyword is used to access base class properties in TypeScript?

The super keyword can be used in expressions to reference base class properties and the base class constructor.

What is class property in TypeScript?

TypeScript supports object-oriented programming features like classes, interfaces, etc. A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object. Typescript gives built in support for this concept called class.

Which method is used to call the base class method from derived class method in TypeScript?

You can call the base class constructor from the child class by using the super() which will execute the constructor of the base class.


1 Answers

use this rather than super :

class A {
    // Setting this to private will cause class B to have a compile error
    public x: string = 'a';
}

class B extends A {
    // constructor(){super();}
    method():string {
        return this.x;
    }
}

var b:B = new B();
alert(b.method());
like image 133
Pascalz Avatar answered Sep 19 '22 10:09

Pascalz