Home > Mobile >  Object is of type 'unknown'. ts(2571) with Vuejs and Typescript
Object is of type 'unknown'. ts(2571) with Vuejs and Typescript

Time:06-03

So I am trying to store JSON data in a variable in a Vue project.

The code to upload and store the file is

<input type="file" id="file" ref="fileSelect" @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 searched online and found various fixes but none of them are working for me I tried adding "useUnknownInCatchVariables": false to tsconfig, it fixes the error momentarily but the error comes back. I also tried 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);
    }
}
    }

But none of these worked. I'll greatly appreciate any suggestion.

CodePudding user response:

Try to cast the type of fileSelect ref yourself like that:

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

I guess you are not reading the result correctly. According to MDN you should just take the result from filereader's result property.

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

  • Related