Home > database >  Calling child static method from parent class
Calling child static method from parent class

Time:11-10


abstract class AbstractView {
    ctx : AbstractView;
    constructor() 
    {
        this.ctx = this.constructor as typeof AbstractView;
    }
    static getStatus() : string
    {
        return 'hi';
    }
}
class testView extends AbstractView {
    static getStatus() : string
    {
        return 'hi2';
    }

}

I am trying to access an overloaded static method from the parent class, however I receive an error message that I don't quite understand.

"Property 'ctx' is missing in type 'typeof AbstractView' but required in type 'AbstractView'"

https://www.typescriptlang.org/play?#code/FAQwRgzgLgTiDGUAE8A2IISQQUrBUAagJYCmA7kgN7BJ0pQAeSAXDnnIiRQNy33wA9gDtoMAK6JBMABQBKJPzo16qpFAAWxCADpEzALzqtuoaNiSo0pBnUBPAA6lBAM3ZiC3cn1UBfJUjQIFDE8EgA5qRQAMpQweIQ8qyBsMTC4QEqanQwUeIwwkgA5FpFPvT -mgYWFCk0F5IpIx1wgAmWLgeXGSUWXRBIWGRMXFQCUlsYmkZqv1queMFxVoATGUB-sC QA

CodePudding user response:

The error message is telling you the problem:

"Property 'ctx' is missing in type 'typeof AbstractView' but required in type 'AbstractView'"

Make them match!

The following compiles, though storing the constructor looks pretty weird.

abstract class AbstractView {
  ctx : typeof AbstractView;
  constructor() {
    this.ctx = this.constructor as typeof AbstractView;
  }
}

CodePudding user response:

Make a typed getter so it has proper type and you don't have to store it

abstract class AbstractView {
    get ctx(): typeof AbstractView {
        return this.constructor as typeof AbstractView;
    }
    static getStatus() : string
    {
        return 'hi';
    }
}
class TestView extends AbstractView {
    static getStatus() : string
    {
        return 'hi2';
    }
}

console.log(new TestView().ctx.getStatus())
// > "hi2"

https://www.typescriptlang.org/play?#code/FAQwRgzgLgTiDGUAE8A2IISQQUrBUAagJYCmA7kgN7BJ1IDmpyiAHgBQCUAXElAJ4AHUgHsAZjjxxEJCtVr1FMZgFcYAOz4ALYhAB08EeugwViETCQY Q0RNwmCs8gG4FdAL7uk0EFGLwjMwAylB KhBcSLwmxOoM3jSKSqoaSADkOuluil5eaBhYACqk0M5IpKxQpOoAJlgO DJklEn0vv6BTFCh4ZGc0T6wcQmKbclIylBqmpnEAEzZ3nnAwIbGIqikeqgiDOzqciVlLVwGUKx63b3T-ZxAA

  • Related