微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

打字稿:在尝试使用构造函数时,在index.d.ts中原型化的类给出“ x不是构造函数”

如何解决打字稿:在尝试使用构造函数时,在index.d.ts中原型化的类给出“ x不是构造函数”

我正在尝试使用定义类svgpath的第三方npm模块SvgPath。类型声明不包括在内,所以我试图编写自己的类型声明。它们位于我的根目录的@types/svgpath/index.d.ts中,我已指示ts编译器在tsconfig.json中将它们与

一起使用
{
  "compilerOptions": 
  {
    ...
    "typeRoots": [ "./@types","./node_modules/@types"]
  }
}

这是在模块中定义类的方式:

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

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

这是index.d.ts文件的外观:

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
    ...
  }
}

这是错误,我在做什么错?这是我第一次为第三方库编写类型声明,因此,如果完全错误,请原谅。

TypeError: svgpath___WEBPACK_IMPORTED_MODULE_9__.SvgPath is not a constructor

解决方法

Typescript自动在 @types 文件夹和导入的 module 文件夹中搜索类型。

svgpath已经有一个.d.ts文件(here),因此无需重写:)。

svgpath声明文件:

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;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。