Property 'share' does not exist on type 'Navigator'

Issue

I need to use WebShareAPI in my Ionic application.

Here is my code as suggested in Introducing the Web Share API

if (window.navigator && window.navigator.share) {
  window.navigator.share({
    title: 'title',
    text: 'description',
    url: 'https://soch.in//',
  })
    .then(() => console.log('Successful share'))
    .catch((error) => console.log('Error sharing', error));
} else {
  alert('share not supported');
}

However, Typescript compilation fails with the following error:

[11:31:11]  typescript: src/pages/channel_home/channel_home.ts, line: 89
            Property 'share' does not exist on type 'Navigator'.

There is a likely reason explained here
DOM lib: add support for navigator.share

However, I would like to know some workaround to make WebShareApi work in my Ionic app in particular, and in any Angular or Typescript app in general.

Solution

Based on this answer,
you can try to define a variable of type any and assign to it your value of Type Navigator. The issue is related to TypeScript typings.

const newVariable: any = window.navigator;

if (newVariable?.share) {
  newVariable.share({
    title: 'title',
    text: 'description',
    url: 'https://soch.in//',
  })
    .then(() => console.log('Successful share'))
    .catch((error) => console.log('Error sharing', error));
} else {
  alert('Share is not supported');
}

Another option would be to extend the interface Navigator as it is suggested in the link I posted above.

Answered By – edkeveked

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published