Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 939
bananaman Avatar asked Nov 25 '18 04:11

bananaman


People also ask

How do you fix Property does not exist on type?

The "Property does not exist on type '{}'" error occurs when we try to access or set a property that is not contained in the object's type. To solve the error, type the object properties explicitly or use a type with variable key names.

Does not exist on type error?

Conclusion # The error "Property 'status' does not exist on type 'Error'" occurs because the status property is not available on the Error interface. To solve the error, add the specific property to the Error interface or create a custom class that extends from Error .


1 Answers

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
like image 187
Titian Cernicova-Dragomir Avatar answered Oct 09 '22 15:10

Titian Cernicova-Dragomir