简体   繁体   English

角度中的“ArrayBuffer”类型不存在属性“split”

[英]Property 'split' does not exist on type 'ArrayBuffer' in angular

I was trying to read a CSV file using Filereader and want to convert the content into an array.我试图使用 Filereader 读取 CSV 文件,并希望将内容转换为数组。 I was able to get the CSV file properly, but whenever I want to convert the content of CSV file into an array I have this error.我能够正确获取 CSV 文件,但是每当我想将 CSV 文件的内容转换为数组时,都会出现此错误。


Why do I have this error and how can i solve it?为什么会出现此错误,我该如何解决?


    ERROR in src/app/app.component.ts(31,10): error TS2314: Generic type 'Array<T>' requires 1 type argument(s).
        src/app/app.component.ts(31,21): error TS2339: Property 'split' does not exist on type 'string | ArrayBuffer'.
          Property 'split' does not exist on type 'ArrayBuffer'.

Here is my app.component.html file:这是我的 app.component.html 文件:

    <nav class="navbar navbar-light bg-light">
      <a class="navbar-brand" href="#">
        <img src="/docs/4.0/assets/brand/bootstrap-solid.svg" width="30" height="30" class="d-inline-block align-top"
          alt="">
        Floor Plan
      </a>
    </nav>

    <div class="card m-5">
      <div class="row row-5">
        <div class="col-4">
          <div class="input-group">
            <div class="custom-file">
              <input type="file" class="custom-file-input" id="inputGroupFile04" (change)="upload($event.target)">
              <label class="custom-file-label" for="inputGroupFile04">Choose file</label>
            </div>
            <div class="input-group-append">
              <button class="btn btn-outline-secondary" type="button" class="btn btn-primary btn-sm">Upload </button>
            </div>
          </div>
        </div>

        <div class="col-8 border border-primary" >
          {{csvContent}}

        </div>

      </div>
    </div>

here is my app.component.ts file:这是我的 app.component.ts 文件:

    export class AppComponent {
      fileToUpload: File = null;
      title = 'floor-plan';
      csvContent: string[] = []



      upload(input: HTMLInputElement) {

        const files = input.files;
        var content = this.csvContent;

        if (files && files.length) {

          const fileToRead = files[0];

          const fileReader = new FileReader();
          fileReader.onload = (event) => {
            this.csvContent = (event.target as FileReader).result.split('\n').map((data) => {
              return data.split(',')
            })

          }

          fileReader.readAsText(fileToRead, "UTF-8");
        }

      }
     }

The type of the FileReader result property is tricky for TypeScript, because it depends on what method you've called elsewhere in the code. FileReader result属性的类型对于 TypeScript 来说很棘手,因为它取决于您在代码的其他地方调用了什么方法。

In your case, you're calling readAsText so you know that result contains a string, not an ArrayBuffer , but TypeScript doesn't know that.在您的情况下,您正在调用readAsText以便您知道result包含一个字符串,而不是一个ArrayBuffer ,但 TypeScript 不知道这一点。

You'll need a type guard or type assertion.您将需要类型保护或类型断言。 For instance, with a type guard:例如,使用类型保护:

fileReader.onload = (event) => {
  const result = fileReader.result;
  if (typeof result !== "string') {
    throw new Error("Unexpected result from FileReader");
  }
  this.csvContent = result.split('\n').map((data) => {
    return data.split(',')
  })
};

Or with a type assertion:或者使用类型断言:

fileReader.onload = (event) => {
  this.csvContent = (fileReader.result as string).split('\n').map((data) => {
    return data.split(',')
  })
};

In both of the examples above, I've used fileReader rather than event.target since the onload handler closes over it.在上面的两个示例中,我使用了fileReader而不是event.target因为onload处理程序关闭了它。

FileReader.result can be either a string or an ArrayBuffer along its life. FileReader.result在其生命周期中可以是字符串或 ArrayBuffer。 It starts being an ArrayBuffer, then, after the file is read, it gets converted to a string.它开始是一个 ArrayBuffer,然后,在读取文件后,它被转换为一个字符串。 The problem is, Typescript isn't happy about applying the .split() method to something that can be an ArrayBuffer at some point in time.问题是,Typescript 不喜欢将.split()方法应用于某个时间点可以是 ArrayBuffer 的东西。

It will be a string at this point of the script execution;在脚本执行的这一点,它将是一个字符串; you know that, but Typescript doesn't.知道,但 Typescript 不知道。

In order to tell this to Typescript, cast it to a string like so :为了将其告知 Typescript,请将其转换为如下所示的字符串:

this.csvContent = <string>((event.target as FileReader).result).split(...)

Then Typescript should stop complaining :)然后打字稿应该停止抱怨:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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