首页 > 解决方案 > 在不破坏现有合约的情况下向导出类型添加函数

问题描述

我想为导出的类型添加一个新函数,该类型已在 prod 中使用,因此不想重命名任何内容或引入重大更改。

import * as BunyanLogger from 'bunyan';
import init from './logger';

export type Logger = BunyanLogger;

我尝试使用接口而不是类型,但它需要我在BunyanLogger.

我想Logger用一种额外的方法来扩展类型,我尝试过如下所示的交集,但也没有用:

export type Logger = BunyanLogger & {
  debugInPlace: (featureRole?:string, ...params: any[]) => void;
};

有没有办法向类型添加额外的方法,而Logger不必重新实现或委托给BunyanLogger类型中的方法?

标签: typescript

解决方案


我能够通过导入整个bunyan命名空间并将其实现为接口来解决此问题。

import Logger from 'bunyan';
import * as bunyanLogger from "bunyan";

export class ExtendedLogger extends Logger implements bunyanLogger {
  constructor(options: Logger.LoggerOptions) {
    super(options);
  }
}

推荐阅读