Argument of type '{ filepath: string; webviewPath: string; }' is not assignable to parameter of type 'Photo'

Viewed 583

so im trying to build the photo-gallery sample project for ionic and im stuck on this error. not sure what i means really. i tried downgrading npm package. didnt work. all the other questions kinda just confuse me more lol so here is the full error:

error TS2345: Argument of type '{ filepath: string; webviewPath: string; }' is not assignable to parameter of type 'Photo'. [ng] Object literal may only specify known properties, and 'filepath' does not exist in type 'Photo'.

2 Answers

I believe they made a mistake in the tutorial. They give the interface the same name as the Photo import from '@capacitor/camera'. Instead, give the interface the name 'UserPhoto'.

My source is looking at the ionic repository for this project on GitHub: https://github.com/ionic-team/tutorial-photo-gallery-angular

You need to change the following in the photo.service.ts file:

export interface UserPhoto {
  filepath: string;
  webviewPath: string;
}

This is at the bottom of the file, outside of the PhotoService class definition.

You also need to define an array of type UserPhoto, not Photo in your PhotoService method. This looks like this:

export class PhotoService {
  
  public photos: UserPhoto[] = [];

I had a similar issue from what I can tell (and this worked for me) the issue is the return type of this function:

  const savePicture = async (
    photo: Photo,
    fileName: string
  ): Promise<Photo> => {
    const base64Data = await base64FromPath(photo.webPath!);
    const savedFile = await Filesystem.writeFile({
      path: fileName,
      data: base64Data,
      directory: Directory.Data,
    });

    // Use webPath to display the new image instead of base64 since it's
    // already loaded into memory
    return {
      filepath: fileName,
      webviewPath: photo.webPath,
    };
  };

It should be Promise<UserPhoto>. We know this because the photos array takes UserPhoto type entries.

So change the above function to:

 const savePicture = async (
    photo: Photo,
    fileName: string
  ): Promise<UserPhoto> => {
    const base64Data = await base64FromPath(photo.webPath!);
    const savedFile = await Filesystem.writeFile({
      path: fileName,
      data: base64Data,
      directory: Directory.Data,
    });

    // Use webPath to display the new image instead of base64 since it's
    // already loaded into memory
    return {
      filepath: fileName,
      webviewPath: photo.webPath,
    };
  };

For reference, I am talking about this tutorial: https://ionicframework.com/docs/react/your-first-app/saving-photos

Their git has working code for the most part so please use it as a reference: https://github.com/ionic-team/tutorial-photo-gallery-react/blob/main/src/hooks/usePhotoGallery.ts

Related