Typescript: Class prototyped in index.d.ts gives "x is not a constructor" when trying to use constructor

535 Views Asked by At

I'm trying to use a third party npm module svgpath that defines a class SvgPath. Type declarations aren't included, so I'm trying to write my own type declarations. They're located in @types/svgpath/index.d.ts in my root directory, and I've instructed the ts compiler to use them in tsconfig.json with

{
  "compilerOptions": 
  {
    ...
    "typeRoots": [ "./@types", "./node_modules/@types"]
  }
}

Here's how the class is defined in the module:

function SvgPath(path) {
  if (!(this instanceof SvgPath)) { return new SvgPath(path); }
  ...
}

// instance member declarations
SvgPath.prototype.toString = function () {
  ...
};

This is what the index.d.ts file looks like:

declare module "svgpath" {
  export class SvgPath {
    constructor (path: string): SvgPath;

    toString(): string;
    abs(): SvgPath;
    scale(sx: number, sy?: number): SvgPath;
    translate(x: number, y?: number): SvgPath;
    rotate(angle: number, rx?: number, ry?: number): SvgPath;
    ... 
    more instance functions
    ...
  }
}

This is the error, what am I doing wrong? It's my first time writing type declarations for a third party library, so please excuse me if this is completely wrong.

TypeError: svgpath___WEBPACK_IMPORTED_MODULE_9__.SvgPath is not a constructor
1

There are 1 best solutions below

0
On

Typescript automatically search types in the @types folder and in imported module folder.

svgpath already has a .d.ts file (here) so no need to rewrite :).

svgpath declaration file:

declare module "svgpath" {
  interface SvgPath {
    (path: string): SvgPath;
    new (path: string): SvgPath;
    abs(): SvgPath;
    scale(sx: number, sy?: number): SvgPath;
    translate(x: number, y?: number): SvgPath;
    rotate(angle: number, rx?: number, ry?: number): SvgPath;
    skewX(degrees: number): SvgPath;
    skewY(degrees: number): SvgPath;
    matrix(m: number[]): SvgPath;
    transform(str: string): SvgPath;
    unshort(): SvgPath;
    unarc(): SvgPath;
    toString(): string;
    round(precision: number): SvgPath;
    iterate(iterator: (segment: any[], index: number, x: number, y: number) => void, keepLazyStack?: boolean): SvgPath;
  }

  const svgPath: SvgPath;
  export = svgPath;
}