【问题标题】:Unable to compile when augmenting OktaAuthService typescript module扩充 OktaAuthService 打字稿模块时无法编译
【发布时间】:2021-01-15 16:26:47
【问题描述】:

场景:

我的项目正在使用最新版本的@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”导入的所有地方编译都会失败

我在这里误会了什么?

【问题讨论】:

    标签: angular typescript okta module-augmentation


    【解决方案1】:

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

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

    【讨论】:

    • 把这个例子作为一个工作例子我有一些挑战(这是我第一次尝试这种事情)这给了我编译时警告 - getUserRole 在 OktaAuthService 类型上不存在 - OktaAuthService 和 OktaAuthServiceCustom 对于演员表的重叠不够 - getUserRole 不是 OktaAuthService.prototype 的成员对不起,你能再扩展一点吗?
    • 所以,试试: interface OktaAuthServiceCustom extends OktaAuthService { prototype: { getUserRole(): Promise; } }
    【解决方案2】:

    答案如下

    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 => {
    });
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-26
      • 2012-09-27
      • 2023-03-24
      • 1970-01-01
      • 2018-04-20
      • 2022-01-05
      • 1970-01-01
      • 2016-11-11
      • 2019-04-17
      相关资源
      最近更新 更多