Type of object is unidentified in Vuejs with Typescript error code ts(2571)

Currently, I am facing a challenge with storing JSON data in a variable within my Vue project.

Below is the code snippet used to upload and store the file:

<input type="file" id="file" ref="fileSelect" class="custom-file-input" @change="showfiles" />

<script lang="ts">
.
.
methods: {
showfiles() {
    let files = this.$refs.fileSelect.files //Error Object is of type 'unknown'. ts(2571) 
    var reader = new FileReader();
    reader.onload = ({ target: { result }}) => { this.p = JSON.parse(result); };
    reader.readAsText(files[0]);
    console.log(this.p) //I am storing JSON data in p
}}

I have explored various online solutions without success. One attempt included adding

 "useUnknownInCatchVariables": false
to tsconfig, which temporarily resolved the error but it resurfaced. Another approach involved using try and catch.

showfiles() {
      try{
        let files = this.$refs.fileSelect.files
        var reader = new FileReader();
        reader.onload = ({ target: { result }}) => { this.p = JSON.parse(result); };
        reader.readAsText(files[0]);
        console.log(this.p)
      }
      catch(err) {
        if (err instanceof Error) { 
          console.log(err.message);
        } else {
          console.log('Unexpected error', err);
        }
      }
}

Unfortunately, none of these approaches yielded the desired outcome. Any suggestions or guidance on resolving this issue would be greatly appreciated.

Answer №1

It's important to properly typecast the fileSelect reference like this:

showFiles() {
  const files = (this.$refs.fileSelect as HTMLInputElement).files // const files: FileList | null
    // ...
  }

Make sure you are interpreting the result correctly. Referencing the filereader's result property is the correct approach according to MDN.

reader.addEventListener("load", () => {
  this.p = JSON.parse(reader.result);
}, false);

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

Creating a consolidated System.config mapping for @angular modules using a single .js file

Currently in the process of developing an Angular 2 application, with the specific requirement to consolidate all resulting Javascript files into a single .js file called output.js. Now, the challenge is to incorporate map configuration within System.conf ...

Utilizing Functions in Next.js with TypeScript: A Guide to Reusability

It is considered a best practice to separate data fetching functions into a folder named services, but I'm having trouble implementing this in my Next.js project. The function works when placed inside the component where I want to render the data, but ...

How can you retrieve the property value from an object stored in a Set?

Consider this scenario: SomeItem represents the model for an object (which could be modeled as an interface in Typescript or as an imaginary item with the form of SomeItem in untyped land). Let's say we have a Set: mySet = new Set([{item: SomeItem, s ...

Problem with Vue Router in Laravel subroute leading to incorrect component discovery

While I had a similar setup working smoothly on another Laravel/Vue project with the main route /, I encountered an issue when grouping the Vue instance under an admin subroute. All paths entered after "admin" would redirect to a PageNotFound component tha ...

tips for sending the chosen product to axios

How can I send the selected item from the dropdown menu to Axios in order to retrieve data? I need to pass the item itself, not just the ID, to the API. <label>City</label> <select @change="getArea()" v-model="key"> <option :valu ...

Capturing user input with Angular Material forms in HTML

In the process of working on a project in Angular, I am utilizing the Angular Material component library. As part of this project, I am creating a form with multiple fields. Everything is functioning properly, however, the layout appears slightly off: ht ...

How to Easily Send Data to a Vue Bootstrap Modal Dialog with Parameters

Currently utilizing the following dependencies in my Vue app: "bootstrap": "^4.6.0", "bootstrap-vue": "^2.21.2", "vue": "^2.6.12", I'm looking to pass a parameter to a Bootstrap Modal Dial ...

Is it possible to make the 'keyof' property optional?

Illustrate an interface in the following way interface Properties { apple?: string banana?: string cherry?: string date: string } Executing this code works as expected type Sample1 = { [P in keyof Properties]: Properties[P] } const s1: Sample1 ...

Maintain synchrony of the state with swiftly unfolding occurrences

I developed a custom hook to keep track of a state variable that increments based on the number of socket events received. However, when I tested by sending 10 simultaneous events, the total value of the state variable ended up being 6, 7, or 8 instead of ...

The component does not contain the specified property

One Angular 4 component that I have is like this: export class MenuComponent { constructor(private menuService: MenuService) { } @Input(nodes):any; getMenu(path:string): void { this.menuService.getData(path).subscribe(data => { // Re ...

How does a brand new installation of VSCode believe it comes pre-equipped with TypeScript capabilities?

Operating on Windows 10 Enterprise, After investing several hours and experimenting on various VMs, Interesting Observation #1 Upon opening a .ts file in vscode, it appears to be recognized as TypeScript 2.3.4 as per the screenshot provided below: http ...

Using Vue.js to eliminate duplicate values from a filtered array of objects

How can I eliminate duplicate data from a v-for loop in Vue.js? I have an array of clients and another array of categories. When filtering the categories based on clientIDs, I noticed that there are duplicates present. Please choose a client from the opti ...

angular primeng table has a checkbox to select all checkboxes

Is there a way to check all checkboxes in a table when the checkbox in the table header is clicked? I am currently utilizing angular 12 and primeNG table for this functionality. <p-table styleClass="text-sm" [value]="value" [loading] ...

Using Ionic2, include NavController into Injectable Service

Having an issue with an Injectable Service in Angular2 with Ionic2 framework. Here is how my service is structured: import {Injectable} from '@angular/core'; import {NavController} from 'ionic-angular'; @Injectable() export class Vie ...

Update the image on a webpage by simply clicking on the current image

Hey there, I'm looking to implement a feature where users can choose an image by clicking on the current image itself. Here's my code snippet. The variable url holds the default image. My goal is to make the current image clickable so that when ...

Is there a way for me to retrieve props that have been passed through the Vue router within a Vue component?

I have configured a route as shown below: { path: 'fit-details', name: 'fit-details', component: Fitment, props: true }, I am passing props via the route using data from the state: this.$router.push({ path: 'fit-details&a ...

Stopping man-in-the-middle breaches through user authentication in Node, Vue, and Passport

Currently, I am developing a web application using Node/Vuejs with Passport handling authentication. However, an issue has come to my attention regarding the security of my authentication setup. Essentially, my Vuex store is hitting a local API endpoint / ...

The attribute 'inventory' cannot be found in the declaration of 'WarehouseModule'

I am facing an issue with my AngularFire setup. I have recently installed the latest version of AngularFire using npm i @angular/fire and have successfully configured Firestore. However, when attempting to load data into my Firestore database, I encounte ...

The attribute interface overload in Typescript is an important concept to

Consider a scenario where there are multiple payload options available: interface IOne { type: 'One', payload: { name: string, age: number } } interface ITwo { type: 'Two', payload: string } declare type TBoth = IOne ...

Can you explain the functionality of this code snippet from a slate.js demonstration?

Trying to grasp the concepts of Slate.js, I delved into the rich text example. Within it, I encountered a code snippet that has left me puzzled. const isBlockActive = (editor, format) => { const [match] = Editor.nodes(editor, { match: n => ...