扩充 OktaAuthService 打字稿模块时无法编译

时间:2021-01-15 16:26:47

标签: angular typescript okta module-augmentation

场景:

我的项目使用的是最新版本的@okta/okta-angular。它导出类“OktaAuthService”。我想使用模块扩充向其添加方法

我的尝试


import { OktaAuthService } from '@okta/okta-angular';

declare module '@okta/okta-angular' {
  interface OktaAuthService {
    getUserRole(): Promise<RoleEnum>;
  } 
}

OktaAuthService.prototype.getUserRole = function (): Promise<Role> {
  return OktaAuthService.prototype.getUser().then(userClaims => {
   //pseudo code
   if user has claim 
     return Role;
   //
  });
}

根据 https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation 这应该可行,但是

  • 该界面似乎在重影导入(TS2693 'OktaAuthService' 仅指一种类型,但在此处用作值(我在其中设置了 getUserRole 函数)

  • 如果我删除了新函数,但保留了模块,我从“@okta/okta-angular”导入的任何地方编译都会失败

我在这里误解了什么?

2 个答案:

答案 0 :(得分:0)

我推荐使用接口继承,例如:

import { OktaAuthService } from '@okta/okta-angular';


interface OktaAuthServiceCustom extends OktaAuthService {
    getUserRole(): Promise<RoleEnum>;
} 


OktaAuthService.prototype.getUserRole = function (): Promise<Role> {
  return (OktaAuthService as OktaAuthServiceCustom).prototype.getUser().then(userClaims => {
   //pseudo code
   if user has claim 
     return Role;
   //
  });
}

答案 1 :(得分:0)

答案如下

import { OktaAuthService } from '@okta/okta-angular';
import { RoleEnum } from '../model/Enums';


declare module '@okta/okta-angular/src/okta/services/okta.service' {
  interface OktaAuthService {
    getUserRole(): Promise<RoleEnum>;
  } 
}

OktaAuthService.prototype.getUserRole = function (): Promise<RoleEnum> {
  return this.getUser().then(userClaims => {
});
}