不能将类型'string'分配给类型'ArrayBuffer | ArrayLike <数字> | SharedArrayBuffer'

时间:2018-11-29 10:29:35

标签: angular typescript

const arr = new Uint8Array(fileReader.result).subarray(0, 4);中,尤其是在第11行的fileReader.result中,出现错误[ts]。

  

'string |类型的参数ArrayBuffer'不能分配给'ArrayBuffer |类型的参数。 ArrayLike | SharedArrayBuffer'。
  不能将类型'string'分配给类型'ArrayBuffer | ArrayLike | SharedArrayBuffer”。

import { AbstractControl } from '@angular/forms';
import { Observable, Observer } from 'rxjs';

export const mimeType = (
    control: AbstractControl
    ): Promise<{ [key: string]: any }> | Observable<{ [key: string]: any }>  => {
              const file = control.value as File;
              const fileReader = new FileReader();
              const frObs = Observable.create(
                (observer: Observer<{ [key: string]: any }>) => {
                  fileReader.addEventListener('loadend', () => {
                    const arr = new Uint8Array(fileReader.result).subarray(0, 4);
                    let header = '';
                    let isValid = false;
                    for (let i = 0; i < arr.length; i++) {
                      header += arr[i].toString(16);
                    }

你们能分享一个解决方案吗?谢谢

3 个答案:

答案 0 :(得分:11)

You can get rid of the error with appropriate type castings: e.g.

...instead of...

this.imagePreview = reader.result;

...try...

this.imagePreview = <string>.reader.result;

...or...

this.imagePreview = reader.result as string;

...or instead of...

const arr = new Uint8Array(fileReader.result).subarray(0, 4);

...write...

const arr = new Uint8Array(<ArrayBuffer>fileReader.result).subarray(0, 4);

...or...

const arr = new Uint8Array(fileReader.result as ArrayBuffer).subarray(0, 4);

I hope that this helps.

答案 1 :(得分:1)

让我们用一个较小的例子来突出这个问题。您应该从以下代码中得到相同的类型错误:

let example: string | ArrayBuffer;

function useArrayBuffer(ab: ArrayBuffer) {
    return ab.byteLength;
}

useArrayBuffer(example);

这是因为example变量可能包含string或和ArrayBuffer如果其中包含一个字符串,则传递给该函数无效,因为该函数只需要ArrayBuffer个参数。

您可以使用类型保护来缩小类型:

let example: string | ArrayBuffer;

function useArrayBuffer(ab: ArrayBuffer) {
    return ab.byteLength;
}

if (typeof example !== 'string') {
    useArrayBuffer(example);
}

如果类型不是字符串,则调用就可以了。

答案 2 :(得分:0)

如果要在从输入文件控件中选择图像后直接显示图像,可以使用类似的内容...

let file = control.value as File;
let reader = new FileReader();
reader.onloadend = () => {
    this.yourVarible = reader.result;;
}
reader.readAsDataURL(file);

让我知道是否需要更多说明

相关问题