0

In the webpart I am currently preparing using SPFX I need to assign some user data into window object:

(<any>window).userDetails = {
      displayName: this.context.pageContext.user.displayName,
      email: this.context.pageContext.user.email,
      loginName: this.context.pageContext.user.loginName
};

However, this.context is getting red marked with the following message:

Property context does not exist on type [component name]

Why is it so?

Note that I have updated all the packages that are originally in package.json to the newest releases (except gulp).

  • It looks like a scoping error. Are you able to provide the rest of the script so we can see what the scope of context is? – BigRaj Jun 7 at 15:20
  • @BigRaj it's just default setup generated by most recent yeoman with the script I enclosed. The only difference is that I updated all the packages except gulp – Mateusz Osuch Jun 8 at 21:31
0

Mateusz,

I couldn't test the code below, but this is how I would approach it:

interface Window {
  userDetails: IUserDetails;
}

declare var window: Window;

interface IUserDetails {
    displayName: string;
    email: string;
    loginName: string;
}

Then use the Window object as follows:

Window.userDetails = {
      displayName: this.context.pageContext.user.displayName,
      email: this.context.pageContext.user.email,
      loginName: this.context.pageContext.user.loginName
};

It is arguably more code, but doing so allows you to fully benefit from TypeScript's strong types.

A word of caution however: be careful of what information you pass in the window variables -- you know, for security reasons.

I hope this helps?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.