1

I'm relatively new to TypeScript. I have a need to implement two route guards that share a common function and state.

When I attempt to extend a injectable class with a constructor, the resulting class does not receive instances of the private members.

Contrived example:

// guard-base.ts

@Injectable()
export abstract class GuardBase {
  constructor(
    private sharedState: SharedState,
  ) {}

  sharedMethod(): boolean {. . .}
}


// authentication-required.guard.ts

@Injectable()
export class RouteGuard extends GuardBase implements CanActivate {
  canActivate(): Promise<boolean> {
    console.log(this);
    // this.sharedState equals undefined at this point
  }
}

Do I have to provide the constructor arguments in the RouteGuard class? What I would like to do is encapsulate all of the imports and the shared method on the base class. Is that possible? If not, what's the best way to accomplish what I would like to do?

1 Answer 1

1

Even other languages expect you to provide a new constructor for the new class (complete with parameters), then pass those parameters into the parent class's constructor to do what you're asking about. http://www.c-sharpcorner.com/UploadFile/5089e0/how-to-use-super-keyword-in-typescript/

Use super(sharedState) to pass the sharedState parameter from the child into the parent's constructor.

If you want to access a member variable from the parent class, use protected instead of private.

Sign up to request clarification or add additional context in comments.

3 Comments

Gotcha. Hmm. I was hoping for something a bit more elegant. Will I have the same issue when extending a non-abstract class?
@Brandon- yes, this is the same for all classes, abstract or concrete.
Thank you for the help. It's not quite as DRY as the Python I used to write, but it will work :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.