简体   繁体   中英

Typescript “Cannot find name <fieldname>”

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

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

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 , eg 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[];
});

我想你只是错过了_tokensthis关键字:

this._tokens = <string[]>data;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM