Extend an incorrect Typescript class definition

妖精的绣舞 提交于 2020-07-08 13:00:34

问题


I'm using the NPM package next-routes in my project. The default export is a class which has a type definition like so:

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

Full file can be found in the package here.

This class definition is missing one of the methods that is exposed in the package's default export called findAndGetUrls. How do I extend the class definition with my own type for this? I thought about creating my own class that implements NextRoutes but defines the missing method definition like so:

import NextRoutes from 'next-routes';

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

But this errors: Function implementation is missing or not immediately following the declaration.

EDIT

My new attempt is to create a typings/next-routes.d.ts file in my project with the following:

import NextRoutes from 'next-routes';

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

  export = Routes;
}

This makes my code happy about the usage of findAndGetUrls, but now it complains that none of the other methods exist so it's not extending the types correctly. e.g. Property 'add' does not exist on type 'Routes'.


回答1:


I've been playing around with it for a while, Typescript won't allow you to redefine the class. But, it seems to work if you re-export the default as an interface instead of a class:

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

You still have to name it Routes so that Typescript knows to merge it with the export default class Routes implements Registry from the next-routes package.

I've only tried this on the latest Typescript version (3.5.2 currently) so YMMV if you're using an older version.



来源:https://stackoverflow.com/questions/56857826/extend-an-incorrect-typescript-class-definition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!