'How do I create a mapper that maps from one interface with optional properties to another without error TS2532: Object is possibly 'undefined' error?

I have a seemingly simple mapping task that is failing when "strictNullChecks": true in tsconfig.json and I'm running a Jest test.

The interfaces come from a private library, and look like the following:

interface Picture {
  readonly title: string;
  readonly metadata?: Metadata;
}

interface Metadata {
  readonly timestamp: string;
  readonly location: string;
}

interface ProfilePicture {
  title: string;
  takenAt?: string;
  geolocation?: string;
}

const mapPictureToProfilePicture = (picture: Picture): ProfilePicture => {
  return {
    title: picture.title,
    ...(picture.metadata ? {
      takenAt: picture.metadata.timestamp,
      geolocation: picture.metadata.location
    } : {})
  }
}

This fails on npm test with the error (where 'picture.metadata' is underlined in red). The test Picture to the function mapPictureToProfilePicture has all the fields.

error TS2532: Object is possibly 'undefined'.
        takenAt: picture.metadata.timestamp
                 ----------------

error TS2532: Object is possibly 'undefined'.
        geolocation: picture.metadata.location
                 ----------------

How should I write the mapper to pass the test? One constraint is that I cannot change the interfaces since they come from a library.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source