Search code examples
typescriptprototype

Typescript - Property does not exist on type when attempting to extend a Class prototype


I'm using Typescript and FabricJS, and I'm attempting to extend the 'Point' class. Here's what it looks like:

export class Point {
    x: number;
    y: number;

    constructor(x: number, y: number);

    add(that: Point): Point;
    addEquals(that: Point): Point;
    // ...(more methods)
}

Here's my attempt to extend it and add a method, in another file:

import { Point } from 'fabric/fabric-impl';

export interface Point {
    a(): any;
}
Point.prototype.a = function () { }; // line that gives error

Here I get the error "[ts] Property 'a' does not exist on type 'Point'. [2339]".

I'm able to get something similar to this working using Typescript's 'extends', by creating a subclass:

interface myPoint {
    a: any;
}

class myPoint extends Point {    
    constructor(x: number, y: number) {
        super(x, y);
    }

}
myPoint.prototype.a = function () { };

This works fine, but I'd rather add directly the method directly to the Point class. Any ideas on what's wrong?


Solution

  • You need to place the Point interface inside a module declaration. This will extend the original type inside the original module instead of declaring a new type:

    import { Point } from 'fabric/fabric-impl';
    
    declare module 'fabric/fabric-impl' {
      export interface Point {
          a(): any;
      }
    }
    Point.prototype.a = function () { }; // ok now