本文介绍了扩展不正确的 Typescript 类定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目中使用 NPM 包 next-routes.默认导出是具有如下类型定义的类:

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.

此类定义缺少包的默认导出中公开的一种方法,称为 findAndGetUrls.为此,我如何使用自己的类型扩展类定义?我想过创建自己的类来实现 NextRoutes 但定义缺少的方法定义如下:

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

但是这个错误:函数实现丢失或没有紧跟在声明之后.

编辑

我的新尝试是在我的项目中创建一个 typings/next-routes.d.ts 文件,其中包含以下内容:

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

这使我的代码对 findAndGetUrls 的使用感到满意,但现在它抱怨没有其他方法存在,因此它没有正确扩展类型.例如Routes"类型上不存在add"属性.

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

推荐答案

我已经玩了一段时间了,Typescript 不允许你重新定义类.但是,如果您将默认值重新导出为 interface 而不是类,它似乎可以工作:

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

您仍然必须将其命名为 Routes 以便 Typescript 知道将其与 next-routesexport default class Routes implements Registry 合并> 包.

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.

我只在最新的 Typescript 版本(目前是 3.5.2)上尝试过这个,如果你使用的是旧版本,那么 YMMV.

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

这篇关于扩展不正确的 Typescript 类定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:32