Skip to content

Provide a way for static method redeclaration #7597

Closed
@iby

Description

@iby

I searched issues and SO, this seems to be something that comes up often, but there's no definitive / any answer to this. I have a proposal.

abstract class Foo {
    public static construct(...args:any[]):Foo {
        return new (<any>this)(...args);
    }
}

class Bar extends Foo {
    protected x:any;
    public constructor(x?:any) {
        super();
        this.x = x;
    }
}

console.log(Bar.construct(1)); // Bar { x: 1 }

In Bar I want to define the same constructor signature for the static construct method. I've tried several things without much success:

  • Interfaces are not an option, explained clearly in Introduce a way to enforce a static contract #1263.
  • Could potentially have an intermediary abstract class with all declarations, but static cannot be abstract. Reasonable.
  • Definition merging sounded promising, but class merging is not allowed. Yet?
  • Override the actual method with an actual implementation – this is not really an answer, it results in too much code that does absolutely nothing.

There's one solution that partially works. Partially, because it gives JetBrains IDE the necessary hinting, that's all I want for now. Besides that it's useless.

declare class Baz extends Foo {
    public static instance(y?:any):Baz;
}

class Baz extends Foo {
    protected y:any;
    public constructor(y?:any) {
        super();
        this.y = y;
    }
}

This fails to compile with Duplicate identifier 'Baz' error. If the ambient declaration moved somewhere else, so that typescript doesn't compile it, then the IDE gets the hinting and tsc doesn't fail. But couldn't that just work like in example above? The rationale is:

  • Ambient declarations don't do much besides type checking and hinting.
  • Can be injected into final declarations produced by compiler.
  • Final declarations are fully reusable.

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions