1

I am pretty new to TypeScript.

I have created a class with some private fields. When I attempt to assign a value to one of the fields in an anonymous callback function within a class method I get the error ...

(TS) Cannot Find the name '_tokens'

I suspect that there is a scoping issue but from my understanding of JavaScript this should not be a problem. I am not sure how to fix it. Any ideas?

See .. "populateTokens()" method for error.

class SingleSignOn {

    private _appTokensURL: string  = "/api/IFSessionCache/Auth/";
    private _tokens: string[];

    /**
     * Initialize an instance of the SingleSignOn class to manage the permissions for the 
     * application associated with the application.
     */
    constructor() {

        this.populateTokens();
    };


    /**
     * Gets a list of permissions tokens associated with the currently logged on user for 
     * the application.
     */
    private getApplicationTokens(): Q.IPromise<{}> {

        return Unique.AJAX.Get(this._appTokensURL, null, ENUMS.AjaxContentTypes.JSON);
    };


    private populateTokens () {

        this.getApplicationTokens().then(
            function (data) {
                _tokens = <string[]>data; // (TS) Cannot find name "_tokens"
            });
    };
};
Gary O. Stenstrom
  • 2,284
  • 9
  • 38
  • 59
  • 1
    There are [several question about this error on Stack Overflow](https://stackoverflow.com/search?q=%5Btypescript%5D+cannot+find+name). Do any of those help you? – Heretic Monkey Nov 13 '18 at 14:32

3 Answers3

2

You are using the wrong syntax:

this.getApplicationTokens().then(
(data) => {
    this._tokens = <string[]>data; // note: turned into an arrow function and added the `this` keyword
});

note if you kept using function() ... syntax the this keyword will not point to the class instance but to the callee

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

greetings

messerbill
  • 5,499
  • 1
  • 27
  • 38
1

Properties of a class do not have a scope, they live as long as the object they belong to live and everything that can access the object can access all its properties too. However properties always have to be accessed on their object, e.g. something._tokens or this._tokens inside methods. Also you have to make sure that this is what you think it is, in your case you have to use an arrow function to access the correct this inside a callback:

this.getApplicationTokens().then( (data) => {
     this._tokens = data as string[];
});
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

I think you're just missing the this keyword from _tokens:

this._tokens = <string[]>data;
qiAlex
  • 4,290
  • 2
  • 19
  • 35
KCM78
  • 3
  • 4
  • this is not enough, the OP also has to change the callback function into an arrow function, otherwise `this` will **not** point to the classes instance – messerbill Nov 13 '18 at 14:35