Typescript的mixin官方applyMixin无法将类称为函数

问题描述

我正在尝试编写一个mixin,我使用的是official typescript handbook中的官方applyMixinsapplyMixins如下所示:

applyMixins.ts

export default function applyMixins(derivedCtor: any,baseCtors: any[]): void {
  baseCtors.forEach((baseCtor) => {
    Object.getownPropertyNames(baseCtor.prototype).forEach((name) => {
      const baseCtorName = Object.getownPropertyDescriptor(
        baseCtor.prototype,name
      );
      if (!baseCtorName) {
        return;
      }
      Object.defineProperty(derivedCtor.prototype,name,baseCtorName);
    });
  });}

我的Mixins看起来像这样

baseApi.ts

export class BaseApiService {
  private headers = {
    Accept: 'application/json','Content-Type': 'application/json',};

  protected client: AxiosInstance;

  public constructor() {
    this.client = axios.create({
      baseURL: process.env.NEXT_PUBLIC_API_URL || 'https://localhost:8000/',headers: this.headers,});
    // ... other code such as request and response interceptor
  }
}

authMixin.ts

export interface IAuthApi {
  login(
    username: string,password: string
  ): Promise<AxiosResponse<LoginResponse>>;
  
  // ... other interfaces
}

export function AuthApiMixin<TBase extends MixinConstructor<BaseApiService>>(
  Base: TBase
) {
  return class extends Base implements IAuthApi {
    public async login(
      username: string,password: string
    ): Promise<AxiosResponse<LoginResponse>> {
      return await this.client.post(`auth/login/`,{
        username: username,password: password,});
    }

    // ... more of other functions
  };
}

api-service.ts

export class ApiService extends BaseApiService {}

export interface ApiService
  extends IAuthApi {}


applyMixins(ApiService,[
  AuthApiMixin
]);

但是,当我尝试使用它时,出现以下错误

Unhandled Runtime Error
TypeError: Cannot call a class as a function

代码看起来就像

const api = new ApiService()
const { data } = api.login(username,password)

我想知道错误的原因是什么?我的Mixin是否必须采用课堂形式?这种混合形式也非常有赖于article

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)