扩展错误的Typescript类定义

JavaScript React.js

JinJin

2020-03-24

在我的项目中使用NPM软件包的下一条路线默认导出是一个类,其类型定义如下:

export default class Routes implements Registry {
  getRequestHandler(app: Server, custom?: HTTPHandler): HTTPHandler;
  add(name: string, pattern?: string, page?: string): this;
  add(pattern: string, page: string): this;
  add(options: { name: string; pattern?: string; page?: string }): this;
  Link: ComponentType<LinkProps>;
  Router: Router;
}

完整文件可在此处的软件包中找到

此类定义缺少包默认导出中称为的方法之一findAndGetUrls我该如何用自己的类型扩展类定义?我考虑过创建自己的类,该类实现NextRoutes,但定义缺少的方法定义,如下所示:

import NextRoutes from 'next-routes';

class Routes implements NextRoutes {
  findAndGetUrls(
    nameOrUrl: string,
    params: {
      [key: string]: string;
    },
   ): void;
}

但是这个错误: Function implementation is missing or not immediately following the declaration.

编辑

我的新尝试是typings/next-routes.d.ts在项目中使用以下内容创建文件:

import NextRoutes from 'next-routes';

declare module 'next-routes' {
  class Routes extends NextRoutes {
    findAndGetUrls(
      nameOrUrl: string,
      params: {
        [key: string]: string;
      },
    ): void;
  }

  export = Routes;
}

这使我的代码对findAndGetUrls的使用感到满意,但是现在它抱怨没有其他方法存在,因此无法正确扩展类型。例如Property 'add' does not exist on type 'Routes'.

第3658篇《扩展错误的Typescript类定义》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
梅Near 2020.03.24

我已经玩了一段时间,Typescript不允许您重新定义类。但是,如果您将默认值重新导出为接口而不是类,则似乎可行

custom-next-routes.d.ts

import NextRoutes, { RouteParams } from "next-routes";

declare module "next-routes" {
    export default interface Routes extends NextRoutes {
        findAndGetUrls(nameOrUrl: string, params: RouteParams): void;
    }
}

你仍然需要它命名Routes,这样 TypeScript知道与合并它export default class Routes implements Registrynext-routes包装。

我仅在最新的Typescript版本(当前为3.5.2)上尝试过此操作,因此,如果您使用的是旧版本,请使用YMMV。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android