Search code examples
angularscopeinstance-variables

Thought I knew what this was


In the code snippet below, I am using a service (Angular) to extract text via a fileReader, using a promise for the async part. The issue I'm having is (I believe) a scope issue and am confused by it. In my component, I declare an instance variable: myDoc : docWrapperClass.

Basically when the file reader extracts the text, I want to assign the results to this local variable. Everything works well until I try to do the assignment. i.e.: this.myDoc = docContents when the promise resolves (Currently comment out).

When the statement is left in the compiler complains: Type '{}' is not assignable to type docWrapperClass: fileName.

There is a property on the docWrapperClass called fileName, but not sure what the {} means. I have commented out the assignment, and then put a breakpoint on the console.log statement in the then() block. When I type "this" in the console, I get undefined, which REALLY confuses me. I would at least expect "this" to a function. My question is how do I assign the docWrapperClass returned from the promise, to the instance variable?

export class myDocComponent implements OnInit {
constructor(private fileReaderService: ReadLocalFileService,
    private textExtractor: TextExtractorServiceService) { }

ngOnInit() { }

docWords: string[] = [];
myDoc: docWrapperClass = null;

selectFile(event: any) {
    console.log("Debug");
    this.fileReaderService.readFile(event.target.files)
    .then((docContents) => {
        console.log("DocContents: " + docContents);
        //this.myDoc = docContents;
    });
}

}


Solution

  • this.fileReaderService.readFile doesn't have a return signature, so when you call then on it's returned value, the Typescript compiler has no idea what it's working with. Therefore, your docContents is of type {}, which is not assignable to your type docWrapperClass.

    One of the big advantages of TypeScript in the first place is type safety. You should define the return type of readFile to be Promise<docWrapperClass>, and likewise define the return type of all of your functions.

    Once the compiler is aware that the method returns a Promise<docWrapperClass, it can properly infer that docContents is assignable to myDoc.