Having trouble compiling the OktaAuthService TypeScript module with augmentation

Question Scenario:

In my current project, I am utilizing the latest version of @okta/okta-angular. This version includes the class 'OktaAuthService'. My goal is to enhance this class by adding a new method using module augmentation.

My Approach So Far


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

Although I referred to https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation for guidance, I encountered some issues:

  • The interface seems to be causing a problem with the import (TS2693 'OktaAuthService' only refers to a type, but is being used as a value here where the getUserRole function is defined)

  • If I exclude the new function but keep the module, compilation errors occur when importing from "@okta/okta-angular"

I'm seeking clarification on what I might be misunderstanding in this context.

Answer №1

One way to enhance your code structure is by utilizing interface inheritance. Here's an example:

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

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

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

Answer №2

The solution eventually unfolded like this

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


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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm struggling to set up break points in both my Angular application and library within VSCode. I can only seem to get them working in either one or the other, but not both

My goal is to enable debugging in vscode for both my Angular 16 application and my library at the same time. The file structure looks like this: ./root ./root/my-app/src ./root/lib/projects/my-lib I have successfully added my lib to the app's pr ...

The 'component' property is not found in the 'IntrinsicAttributes' type in this context

I am facing an issue with a component that is not compiling properly: export default function MobileNav({routes, currentRouteIndex, handlePressedRoutedIndex}: MobileNavProp) { ... return ( <React.Fragment> ... ...

Transfer highlighted checkboxes between two containers. Any deselected checkboxes in the second container should also be removed from the initial container

I have successfully populated the necessary checkboxes within a single div element. Furthermore, I have been able to save the selected checkboxes to an object. https://i.sstatic.net/Pn0pu.png I am interested in learning how to display this object (check ...

How to activate the close function of ionic-datepicker when tapping the hardware back button in Ionic 4

Utilizing ionic-datepicker in my app (ionic v-4), here is the corresponding template: <ion-datetime formControlName="meeting_date" display-format="MMM DD, YYYY"></ion-datetime> The datepicker (i.e ion-datetime) closes upon clicking cancel/do ...

Is it possible to retrieve the form value in Angular that is different from what is displayed?

Is there a way in Angular to retrieve form values differently than how they are displayed? For example, let's say you have an Angular FormInput that displays the value "3,567.56 $" to the user. <input formInputControl="price" money> I want th ...

​Troubleshooting findOneAndUpdate in Next.js without using instances of the class - still no success

After successfully connecting to my MongoDB database and logging the confirmation, I attempted to use the updateUser function that incorporates findOneAndUpdate from Mongoose. Unfortunately, I ran into the following errors: Error: _models_user_model__WEBPA ...

How can you efficiently refresh cached data for multiple related queries after a single mutation in react-query?

Within my codebase, I have a few queries that need to be addressed: Retrieve all articles useInfiniteQuery( ['articles', { pageSize: props.pageSize }], queryFn ); Fetch articles within a specific category useInfiniteQuery( [&ap ...

Discovering the general function types in TypeScript

Currently, I am in the process of developing a function to generate Redux actions (similar to createAction from redux toolkit). My goal is to create a function that can produce action generators based on the types provided to the creator function. const c ...

Verifying TypeScript Class Instances with Node Module Type Checking

My current task involves converting our Vanilla JS node modules to TypeScript. I have rewritten them as classes, added new functionality, created a legacy wrapper, and set up the corresponding Webpack configuration. However, I am facing an issue with singl ...

Encountered an error while trying to generate the Component class for the ColorlibStepIcon from Material UI in TypeScript

I am trying to convert the ColorlibStepIcon functional component into a class component for my Stepper. Unfortunately, I have not been successful and keep encountering errors. I have attempted some changes but it is still not working as expected. You can ...

The project graph creation for NX has encountered a setback and was unable to be completed. The worker has halted with exit

I've encountered an issue with my Angular project while using nx. Upon running npm install, I received the following error: > NX Nx Daemon was not able to compute the project graph. Log file with the error: ...\node_modules\.cache ...

Retrieve the dimensions of a child component when NgIf condition is met

I am facing a situation where I have a main component with a child component that is populated using NgFor. To control the visibility of the child, the parent sets a property called childIsVisible to false and binds it to the child using *ngIf="childIsVisi ...

Tips for implementing generics in an abstract class that extends a React Component

I am in the process of developing a unique abstract class that extends a React Component. My goal is to establish default Props while allowing the components that extend the abstract class to supply their own props. interface Props { ...

Implementing the click event in angular2-openlayers will display the information for the selected marker

Exploring Angular and Openlayers (3) is a new endeavor for me. Recently, I stumbled upon this open source library that conveniently wraps Openlayers within Angular. A straightforward question has come to mind: How can I detect when a user clicks on a gene ...

I'm facing an issue when trying to convert a string to JSON in Ionic2

When attempting to retrieve json in the code below, an unexpected "space" is present after the opening brace and before the closing one: { "address": ......, "filename": image.png, "price": 12 } If I use res.json() in the following code, it result ...

Unleashing the full power of TypeScript: Harnessing Array.prototype.reduce with Generics

Attempting to standardize data using Array.prototype.reduce. Puzzled by how I can bypass "type-checking" in the reduce function. My interfaces: interface Dict<T> { [key:string]: T; } interface InnerData { id: string; value: number; } inter ...

Omitting ts/js files from the package with webpack

I am relatively new to webpack and currently working on an angular2 application with webpack. Our requirement includes having a settings file that should not be bundled, allowing the URL in the settings.js file to be changed after bundling. Here is the co ...

I always encounter issues when trying to submit my form using a reactive form

I seem to be facing an issue with submitting a form in Angular. Although this isn't my first project, it's the first time encountering this specific problem. While I have used a FormBuilder to construct my form and validated it in the HTML, clic ...

Angular is having trouble properly rendering the Array Description

I'm currently working on a project using .net core MVC with an Angular frontend. I am facing an issue where the description of parameter arrays is not displayed in the output, even though single parameters display correctly. How can I resolve this pro ...

"Subscribing in interceptor doesn't seem to have any effect

I am currently facing an issue where I try to refresh a token using an API call, but the token does not get refreshed and the logs are not appearing as expected. In my code, I have implemented a timeout for testing purposes to trigger the token refresh and ...