Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript declaration extending class with static method.

Tags:

typescript

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?

like image 655
Clark Avatar asked Mar 18 '26 22:03

Clark


1 Answers

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;
}
like image 54
basarat Avatar answered Mar 20 '26 10:03

basarat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!