Latest Typescript 1.8.4 compilation issue: "Compilation Error: Property 'result' is not found on the 'EventTarget' type."

I recently made the switch to using TypeScript in my Durandal application, upgrading from VS-2012 to VS-2015 and subsequently from TypeScript 0.9 to TypeScript 1.8.4. While transitioning, I encountered numerous build errors which I managed to resolve, except for one persisting issue related to types of Events.

ERROR: " Build: Property 'result' does not exist on type 'EventTarget' "

The problematic code snippet is as follows:

var reader:any,
target:EventTarget;

reader= new FileReader();
reader.onload = function (imgsrc){
    var fileUrl = imgsrc.target.result;
}

The variable "Imgsrc" is of type event.

This code worked perfectly fine with TypeScript 0.9, but after upgrading to 1.8.4, it started throwing an error stating that 'result' does not exist on type 'EventTarget'. If anyone has a solution to this, please help me out.

Note: The declaration "target:EventTarget" originates from lib.d.ts

Answer №1

Opting for FileReader.result over event.target.result is a more efficient approach.

Take this as an example,

const myFileReader: FileReader = new FileReader();

myFileReader.onload = (event: Event) => {
   event.target.result; // Avoid using this
   myFileReader.result; // This is the correct way
};

Answer №2

When it comes to any as medication (working for almost anything, but where does TypeScript come in)... there has been a reported issue with a nice workaround that is quite TypeScript-ish.

Proposed Change for currentTarget in Event interface for lib.d.ts

Let me quote from the discussion:

I encountered this TS2339: Property 'result' does not exist on type 'EventTarget' in JS FileReader onload, and another warning for getSummary() on the event passed to FileReader's onerror.

To avoid these errors and suppress the red squiggly lines, I have implemented the following workaround:

interface FileReaderEventTarget extends EventTarget {
    result:string
}

interface FileReaderEvent extends Event {
    target: FileReaderEventTarget;
    getMessage():string;
}

In my application code:

reader.onload = function(fre:FileReaderEvent) {
    var data = JSON.parse(fre.target.result);
    ...
}

For now, we continue working with the known interface until any changes are made in lib.d.ts

Update December 2019:

If you encounter the error message:

error TS2322: Type '(this: FileReader, e: FileReaderEvent) => void' is not assignable to type '(this: FileReader, ev: ProgressEvent) => any'.

In such case, simply replace

 interface FileReaderEvent extends Event {

with

 interface FileReaderEvent extends ProgressEvent {

Answer №3

Initially, my previous type script had the parameter "imgsrc" with a default type.

However, I decided to change it to (imgsrc:any) and it is now functioning properly.

var reader:any,
target:EventTarget;
reader= new FileReader();
reader.onload = function (imgsrc:any){
var fileUrl = imgsrc.target.result;
}

Answer №4

The problem lies within the TypeScript definitions. One quick fix is:

let element: any = e.element; //<-- Using (any) here will silence the compiler!
let data: string = element.value;

Answer №5

To inform TypScript of the expected type, simply specify it.

Check out this solution:

let writer = new FileWriter();
writer.onload = function (event){
    let documentUrl = (<FileWriter>event.target).result;
}

In this scenario, you have the option to use writer.result as well.

Answer №6

If you're looking for a straightforward solution, then I found that this method worked perfectly for me.

var reader: any,
target: EventTarget;
reader = new FileReader();
reader.onload = function (imgsrc) {
    // var fileUrl = imgsrc.target.result; //change to
    var fileUrl = (imgsrc.target as FileReader).result; //cast to correct type
}

Answer №7

Upon examination of the lib.dom.d.ts file, the solution becomes clear:

let reader: FileReader = new FileReader();

reader.onload = (event: ProgressEvent<FileReader>) => {
   event.target.result; // This is permissible
};

Answer №8

It was successful for me today with TypeScript 2.1.1

interface EventTarget { result: any; }

Answer №9

When encountering this issue
The error "Type 'string | ArrayBuffer' is not assignable to type 'string'. Type 'ArrayBuffer' is not assignable to type 'string'" may appear

fileReader.result+' ';//this code snippet is valid
fileReader.result; //however, this one is invalid

Answer №10

After encountering issues with IndexedDB similar to those mentioned above, I found a solution that worked for me. By simply changing the arguments of the (event) functions to (event: any), I was able to bypass the type errors.

Here is an example of the code:

let request = window.indexedDB.open('userChannels', 3);

request.onerror = function(event: any ) {
    console.log('ERROR: Failed to create userChannels local DB' + event.target.errorCode)
};

request.onsuccess = function(event: any) {
   let db = event.target.result;
   console.log('SUCCESS: Created userChannels local DB')
};

Answer №11

Encountered a similar issue in my Angular project while using the FileReader.

The solution turned out to be quite straightforward (thanks to Typescript's strong typing). You just need to utilize the ProgressEvent<FileReader>. This can be located in the lib.dom.d.ts file within your Typescript installation, making it easily accessible if you include

lib: {
"dom"
}

in your tsconfig.json.

Below is the snippet of code where I had to implement this:

function read(file: File) {
  const fileReader = new FileReader();
  fileReader.onloadend = function (e: ProgressEvent<FileReader>) {
    const arr = (new Uint8Array(parseInt(e.target.result.toString(), 10))).subarray(0, 4);
    var header = "";
    for (var i = 0; i < arr.length; i++) {
      header += arr[i].toString(16);
    }
    console.log(header);

    // Check the file signature against known types

  };
  fileReader.readAsArrayBuffer(file);
}

Answer №12

in place of

    this.localDbRequest.onsuccess = function (event) {
      const db = event.target.result;
    };

try

   this.localDbRequest.onsuccess = function (event) {
     const db = this.result;
   };

Answer №13

To avoid errors until resolved, you can access the target object in the following way:

fileReader = new FileReader();
fileReader.onload = function (image){
    var url = image.target["result"];
}

Interpret the target as a JavaScript Object

Answer №14

this is an important update in JavaScript/TypeScript.

To adapt to this change, simply substitute "event.target.result" with "this.result".

In this context, "this" specifically refers to the interface "MSBaseReader".

Here is a snippet of how I implemented this change:

      let reader = new FileReader();
      let profile: TransProfile = new TransProfile();

      reader.onload = function(event){
        profile.avatar = new Uint8Array(this.result);
      }

      reader.onerror = function(event){
      }

      this.photoLib.getPhoto(item)
        .then(blob => reader.readAsArrayBuffer(blob))
        .then(() => this.doUpload(profile));

Definition of "MSBaseReader" interface:

interface MSBaseReader {
    // Interface properties and methods listed here
}

Definition of "FileReader" interface:

interface FileReader extends EventTarget, MSBaseReader {
    // More interface properties and methods specified here
}

It's worth mentioning that due to the shift in the context of "this" inside "onload()", you won't be able to directly access your class-based definitions within "reader.onload = function(event){...". This means that you can't use "this.class-property" syntax to refer to your class properties. Instead, you'll need to define local variables like I did with "profile" in the example above.

Answer №15

Give this a shot.

event.target["result"]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular Relationships (Error 400 - Invalid Request)

I am encountering a significant issue when trying to add data to a table connected with the Spring database. The problem arises specifically when I attempt to add new data to the table, but encounter errors when choosing options from a Combo Box. This is t ...

Is it feasible for the Drawer to be a fixed feature that sits atop the content?

I am looking to have a compact drawer positioned on the left side of my screen, similar to the example shown in the Material UI Documentation: https://i.sstatic.net/W21Kd.png However, I would like it to float over the content (like the variant="temporary ...

"Utilizing Postgresql with TypeORM for filtering many-to-many relationships

I have two entities that are connected with a ManyToMany relationship: // Branch entity @ManyToMany( (type) => User, (e) => e.branches ) users: User[]; // User entity @ManyToMany( (type) => Branch, (e) ...

Top method for changing Enum to Set in TypeScript

Take a look at the enum below: enum Animes { OnePiece = 'One Piece', Naruto = 'Naruto', Bleach = 'Bleach' } How can we efficiently transform this enum into a Set? ...

What is the overlay feature in Material-UI dialogs?

I recently started using the React-Redux Material-UI package found at http://www.material-ui.com/#/components/dialog My goal is to implement a grey overlay that blankets the entire dialog element, complete with a circular loading indicator after the user ...

TypeScript Add Extract Kind

I am currently working on implementing a function called sumPluck. This function will allow the user to specify a property of type number from an object in an array, and then calculate the sum of all those properties. For example: type A = { prop: number ...

Is it possible to deactivate input elements within a TypeScript file?

Is it possible to disable an HTML input element using a condition specified in a TS file? ...

Creating a contravariant function member in TypeScript?

I am facing a challenge with a class that contains a member which is a function taking an instance of the same class: class Super { public member: (x: Super) => void = function(){} use() {const f = this.member; f(this)} } However, I need the me ...

Filtering an array in Angular based on two specific property values

I am facing a challenge with deleting items from an array based on two property values. If we were to compare it to the classic Sql delete command, the equivalent would look something like this: DELETE oImages WHERE idOffertRow = 1 and idProductImage = 2 ...

Encountering an unexpected termination error when using Typescript, pg, Express, and Psql within a Docker container: "Error: Connection terminated unexpectedly"

I am facing an issue with connecting to my database running on a Docker container using a postgres image: docker run --name postgres-container -p 2345:2345 -e POSTGRES_PASSWORD=password123 -e POSTGRES_USER=admin -d postgres The TypeScript code I have is i ...

Writing TypeScript, Vue, and playing around with experimental decorators

After creating a Vue project through Vue-CLI v3.0.0-beta.15, the project runs smoothly when using npm run serve. However, TypeScript displays an error message stating that support for decorators is experimental and subject to change in a future release, bu ...

BrowserRouter - The type '{ children: Element; }' is not compatible with the type 'IntrinsicAttributes', as they do not share any properties in common

After upgrading to React version 18, I encountered a type error with the BrowserRouter component. Despite trying various approaches, I am unable to pinpoint the root of the problem. Here is the error that pops up during debugging: Overload 1 of 2, &a ...

Angular 11 now includes the ability to implement lazy loading for modules

Here is the configuration of my app-routing.module.ts: const routes: Routes = [ { path: 'login', component: LoginComponent }, { path: '', canActivate: [AuthGuard], component: HomeComponent, children ...

Error encountered in ngtsc(2345) where an argument of type 'Event' is being used instead of an expected parameter type of 'SortEvent'

I recently started using angular and encountered an issue while trying to sort columns. The error message I received was: Argument of type 'Event' is not assignable to parameter of type 'SortEvent'. Type 'Event' is missing t ...

Issue encountered while trying to import jszip in Angular project

Encountering an error when trying to import jszip into my TypeScript component file. After successfully running npm install jszip and confirming the package is properly installed, I proceed to import it using: import * as JSZip from 'jszip'; Th ...

Issue with vue-class-component: encountering TS2339 error when trying to call a method within

My vuejs application is being built using vue-cli-service. After a successful build, I encountered TS2339 errors in my webstorm IDE: Test.vue: <template> <div>{{method()}}</div> </template> <script lang="ts"> impor ...

What is the best way to determine the specific type of a value that is part of a union type?

Utilizing @azure/msal-react and @azure/msal-browser for implementing authentication in a React project with Typescript. The issue arises when TypeScript identifies event.payload as type EventPayload, but does not allow checking the exact type (e.g. Authen ...

Guide to incorporating ThreeJS Collada loader with TypeScript / Angular CLI

I currently have three plugins installed: node_modules/three My Collada loader was also successfully installed in: node_modules/three-collada-loader It seems that the typings already include definitions for the Collada loader as well: node_modules/@ty ...

transform array elements into an object

I encountered the following code snippet: const calcRowCssClasses = (<string[]>context.dataItem.cssClasses).map( (cssClass) => { return { [cssClass]: true }; } ); This code block generates an array of objects like ...

Tips for concealing boostrap spinners

Within the main component, I have an @Input() alkatreszList$!: Observable<any[]>; that gets passed into the child component input as @Input() item: any; using the item object: <div class="container-fluid"> <div class="row ...