简体   繁体   English

扩充 OktaAuthService typescript 模块时无法编译

[英]Unable to compile when augmenting OktaAuthService typescript module

Scenario:设想:

My project is using the latest version of @okta/okta-angular.我的项目正在使用最新版本的@okta/okta-angular。 It exports the class 'OktaAuthService'.它导出 class 'OktaAuthService'。 I would like to use module augmentation to add a method to it我想使用模块扩充来添加一个方法

What I've tried我试过的


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

According to https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation this should work, however根据https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation这应该可以,但是

  • the interface appears to be ghosting the import (TS2693 'OktaAuthService' only refers to a type, but is being used as a value here (where I set the getUserRole function)该界面似乎在重影导入(TS2693 'OktaAuthService' 仅指一种类型,但在此处用作值(我在其中设置了 getUserRole 函数)

  • If I remove the new function, but leave the module, compilation fails everywhere I import from "@okta/okta-angular"如果我删除了新的 function,但离开了模块,那么我从“@okta/okta-angular”导入的所有地方编译都会失败

What am I misunderstanding here?我在这里有什么误解?

I recommend to use interface inheritance, example:我推荐使用接口inheritance,例如:

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

The answer ended up being as follows答案最终如下

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM