Angular Error: Type 'Observable<number | undefined>' is not assignable to type 'Observable<number>'

I am creating a service to upload files to firebase storage in Angular, but the latest version of typescript requires the declarations to be more specific, so it does not allow me to have a variable of type number that is initialized as undefined and I get the following error when trying to get the file upload percentage:

Type 'Observable<number | undefined>' is not assignable to type 'Observable'. Type 'number | undefined' is not assignable to type 'number'. Type 'undefined' is not assignable to type 'number'.ts(2322)**

this is my fileItem class:

export class FileItem {
    public name: string;
    public uploading: boolean = false;
    public uploadPercent?: Observable<number>;
    public downloadURL?: Observable<string>;

    constructor(public file: File = file) {
        this.name = file.name;
    }

and this is the line of code that I don't know how to modify:

item.uploadPercent = task.percentageChanges()

The complete function is:

uploadFiles(folderPath: string, files: FileItem[]) {
    for (const item of files) {
      item.uploading = true;

      const filePath = this.generateFileName(folderPath, item.name);
      const fileRef = this.storage.ref(filePath);
      const task = this.storage.upload(filePath, item.file);

      item.uploadPercent = task.percentageChanges()
      task
        .snapshotChanges()
        .pipe(
          finalize(() => {
            item.downloadURL = fileRef.getDownloadURL();
            item.uploading = false;
          })
        )
        .subscribe();
    }

The .percentageChanges() method returns the following:

percentageChanges(): observable<number | undefined>;

Upvotes: 1

Views: 1897

Answers (1)

I assume that the error is from this line (if it's not, please add the exact part of code where the error tells you (it tells you the number line).

Then...It allows you to declare uploadPercent as this?:

public uploadPercent?: Observable<number|undefined>;

If it does, I guess that with this little change you will have solved de error.

If it doesn't, try with:

public uploadPercent?: Observable<number|any>;

If none of these solutions works, show the exact code part which fails, and the solution will pass through change when returns 'Observable<number | undefined>' to force in a way to return 'Observable< number>'

Upvotes: 1

Related Questions