Typescript: Inheritance and static members

Created on 8 Dec 2015  路  1Comment  路  Source: microsoft/TypeScript

I think that is useful to access to static members :

  • from instances
  • from sub classes

Below an example:

class A {
  protected static type: string;

 public log(): string {
    console.log(this.type);
  }
}

class B extends A {
  protected static type: string = 'C';
}

class C extends A {
  protected static type: string = 'C';
}

b = new B();
b.log(); // => 'B'

c = new C();
c.log(); // => 'C'
By Design Declined Suggestion

Most helpful comment

We can't do it the way you suggest since this.type is used to access an _instance_ property named type, not a _static_ property.

However, your example works if you write it as follows:

class A {
  "constructor": typeof A;  // Explicitly declare constructor property
  protected static type: string;

  public log() {
    console.log(this.constructor.type);  // Access actual constructor object
  }
}

class B extends A {
  protected static type: string = 'B';
}

class C extends A {
  protected static type: string = 'C';
}

let b = new B();
b.log(); // => 'B'

let c = new C();
c.log(); // => 'C'

By default the constructor property of an instance is of type Function, but you can specialize it in a class by manually declaring it. Once you do that you can access the statics through this.constructor.xxx, and you'll get the properties of the constructor object that actually created the instance (i.e. the derived constructor object).

>All comments

We can't do it the way you suggest since this.type is used to access an _instance_ property named type, not a _static_ property.

However, your example works if you write it as follows:

class A {
  "constructor": typeof A;  // Explicitly declare constructor property
  protected static type: string;

  public log() {
    console.log(this.constructor.type);  // Access actual constructor object
  }
}

class B extends A {
  protected static type: string = 'B';
}

class C extends A {
  protected static type: string = 'C';
}

let b = new B();
b.log(); // => 'B'

let c = new C();
c.log(); // => 'C'

By default the constructor property of an instance is of type Function, but you can specialize it in a class by manually declaring it. Once you do that you can access the statics through this.constructor.xxx, and you'll get the properties of the constructor object that actually created the instance (i.e. the derived constructor object).

Was this page helpful?
0 / 5 - 0 ratings