How to Pass Dynamic Data to an Extended Typescript Class

Can anyone provide some assistance with this issue?

I am working on extending a class from a 3rd party and I need to pass data dynamically. This is the class structure:

class AuthGuardNew extends AuthGuard("Needs changing") {


}

What I would like to achieve is to do something like this:

new AuthGuardNew("Something different")

This way, "Something different" will be passed to the extended class instead of "Needs Changing."

If I use a constructor like this:

constructor(type:string) {

}

But how can I pass this into AuthGuard when it has already been extended?

Any suggestions or ideas to tackle this challenge are greatly appreciated.

Thank you in advance.

UPDATE

When I try to implement the following:

export class AuthGuardNew extends AuthGuard {
  constructor(type?: string) {
    super(type)
  }

I encounter a typescript error stating that:

Type '(type?: string | undefined) => Type' is not a constructor function type.

Answer №1

Simply put, it is not possible to extend AuthGuard directly because it is a function that generates a class, not the actual class itself. The class only gets created when the value of type is known.

Instead, you can create a new function that constructs the class after determining the value of type.

const AuthGuardNew = (type?: string) =>
    class extends AuthGuard(type || 'Needs changing') { 
        // Feel free to customize as needed, you are creating a new class
        myExtension(): number {
            return 10;
        }
    }

AuthGuardNew is another function that produces a class, not an actual class.

const SomethingDifferentAuthGuard = AuthGuardNew('Something different');

// Now SomethingDifferentAuthGuard is a class that extends AuthGuard('Something different')
// and we can instantiate and utilize it accordingly
console.log(new SomethingDifferentAuthGuard().myExtension())

Answer №2

To invoke the parent constructor, you can use the super keyword within the child class's constructor like so:

class ExtendedAuthGuard extends AuthGuard {
    constructor(userType: string) {
        super(userType);
    }
}

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

Protractor encountering a session creation exception for chrome

Encountering an error while trying to execute a Protractor test in Chrome. Here is my conf.ts file: import {Config} from 'protractor' export let config: Config = { framework: 'jasmine', multiCapabilities: [ { ...

The BehaviorSubject will consistently emit identical values to each subscription

I am currently facing an issue with the BehaviorSubject where it emits a value for every subscription. This means that if I have, for example, 2 subscriptions to this.projectService.projectState$ streams using methods like async or tap, the projectState$ e ...

AngularJS Dilemma: Virtual Machine Data Set but No Rendering in Sight

Below is the AngularJS controller code written in Typescript: /// <reference path='../../definitions.d.ts' /> module baseApp.viewControls.products { export interface IProductsScope extends IAppScope { vm: { product ...

Securing pathways in Next.js using middleware and Next-Auth

Hey there, I'm currently working on adding some route protection in NextJS using middleware for authentication with next-auth. According to the documentation, this is what my middleware.ts file should look like: export { default } from "next-auth ...

The Angular JavaScript page successfully compiles, yet displays only a blank screen

I am facing an issue with my Angular app where it compiles successfully, but the HTML page appears blank and my application is not displaying properly. I have encountered similar problems in the past which were often related to Imports, but this time I&apo ...

How can I fetch a file using a JavaScript function in Pug/Angular?

Within the Angular7/Pug application, there was previously a file download link implemented in table.component.pug like this: div p File to download: a([href]="downloadLink", download="table.xlsx") some-icon span some-text Now, I a ...

Can you explain the significance of having two consecutive => symbols?

While I understand lambdas and function types, I am unsure about the following expression: displayFunc: (string) => string = x => x; I find the two symbols "=>" puzzling. Can someone explain what this means? ...

The style fails to load correctly upon the page's initial loading

I am utilizing <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4d26282823603e212429283f0d7b63756378">[email protected]</a> in a <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="026c677a76 ...

Using Typescript in conjunction with nodemon and VS Code for seamless integration of declaration merging

After adding a middleware to my express app app.use(function(req: express.Request, res: express.Response, next: express.NextFunction) { req.rawBody = 'hello2'; next(); }); I also included custom.d.ts declare namespace Express { expor ...

Transforming a TypeScript enum into an array of objects

My enum is defined in this structure: export enum GoalProgressMeasurements { Percentage = 1, Numeric_Target = 2, Completed_Tasks = 3, Average_Milestone_Progress = 4, Not_Measured = 5 } However, I want to transform it into an object ar ...

Guide on dynamically applying a CSS rule to an HTML element using programming techniques

Currently working with Angular 6 and Typescript, I am facing a unique challenge. My task involves adding a specific CSS rule to the host of a component that I am currently developing. Unfortunately, applying this rule systematically is not an option. Inste ...

Enable a fraction of a category

Imagine having a structure like this interface User { name: string; email: string; } along with a function like this updateUser(user: User) { } As currently defined, updateUser cannot accept only a name (updateUser({name: 'Anna'} would fa ...

Troubles encountered while trying to dispatch an action in an Angular ngrx unit test

I have a situation where a component is fetching data from an API, but the data is only needed once, so I have opted not to use a reducer and selector for it. Instead, I am using actions and effects to handle the API call. Here is the code I am trying to ...

The yarn/npm package manager seems to be utilizing outdated code in an inexplicable way when paired with mocha and typescript

I recently encountered a strange issue that has left me scratching my head. When I manually run my test command, I receive two test results. However, when I execute the same command in a yarn/npm script, only one result is displayed. Has anyone else experi ...

MatSort: the name of the property is not the same as matColumnDef -> causing issues

Is it possible to use matSort in an Angular table to sort a column where the property name differs from the matColumnDef? <ng-container matColumnDef="name"> <th mat-header-cell *matHeaderCellDef mat-sort-header>TEST</th> ...

Angular HTTP requests are failing to function properly, although they are successful when made through Postman

I am attempting to send an HTTP GET request using the specified URL: private materialsAPI='https://localhost:5001/api/material'; setPrice(id: any, price: any): Observable<any> { const url = `${this.materialsURL}/${id}/price/${price}`; ...

Steps to prevent subfolder imports in my npm package

My npm package is built using: typescript webpack webpack.config: {... entry: './src/index.ts } library tree: - package.json - src - - index.ts - - ...all_my_code... I have all my library functionality and types exported from the index.ts file. T ...

Incorporating a YouTube channel onto a website with React and Typescript, only to be greeted with a

After executing the following code snippet, everything runs smoothly, except for the YouTube player displaying a 404 error. I suspect that there might be an issue with the embedded URL. In the code below, I define a constant called YouTubePlayer which lo ...

Utilizing ReactJS and TypeScript to retrieve a random value from an array

I have created a project similar to a "ToDo" list, but instead of tasks, it's a list of names. I can input a name and add it to the array, as well as delete each item. Now, I want to implement a button that randomly selects one of the names in the ar ...

The TSC directive requiring 372 seconds for execution

I recently discovered that my TypeScript Firebase repository, used for cloud functions and consisting of only 6 files in the src directory, was taking an unusually long time to compile when running the tsc command. To investigate further, I executed it wit ...