Clark
Clark

Reputation: 2678

TypeScript declaration extending class with static method.

I am looking for some advice on how to handle this situation correctly.

I have something.d.ts

export class Sprite {

    static fromFrame(frameId: string): Sprite;
    static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite;

}

export class TilingSprite extends Sprite {

    static fromFrame(frameId: string, width?: number, height?: number): TilingSprite;
    static fromImage(imageId: string, width?: number, height?: number, crossorigin?: boolean, scaleMode?: number): TilingSprite;

}

In this case, I get the following error:

Error   40  Class static side 'typeof TilingSprite' incorrectly extends base class static side 'typeof Sprite'.   Types of property 'fromImage' are incompatible.
    Type '(imageId: string, width?: number, height?: number, crossorigin?: boolean, scaleMode?: number) => ...' is not assignable to type '(imageId: string, crossorigin?: boolean, scaleMode?: number)
=> Sprite'.
      Types of parameters 'width' and 'crossorigin' are incompatible.
        Type 'number' is not assignable to type 'boolean'.

I cannot really see a way to solve the issue or, it is different behaviour from what I would expect.

How could I cleanly solve this signature?

Upvotes: 3

Views: 2585

Answers (1)

basarat
basarat

Reputation: 276299

How could I cleanly solve this signature

Not cleanly but can be done with function overloading. e.g.:

declare class Sprite {
    static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite;
}

declare class TilingSprite extends Sprite {
    static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite;
    static fromImage(imageId: string, width?: number, height?: number, crossorigin?: boolean, scaleMode?: number): TilingSprite;
}

Upvotes: 4

Related Questions