iOS DeviceOrientationEvent API & Typescript

931 Views Asked by At

I have the following setup for an @on:clock callback that is designed to ask the user for permission to the DeviceOrientationEvent API for iOS Safari devices:

const setDeviceOrientationPermission = async () => {
  if (typeof DeviceOrientationEvent.requestPermission === 'function') {
    deviceOrientationPermissionState.value = await DeviceOrientationEvent.requestPermission()
  }
}

As I am in Vue 3 + Tyepscript world when doing this, I set deviceOrientationPermissionState which is a ref (More on refs here: https://v3.vuejs.org/guide/reactivity-fundamentals.html)

This code is all working, when loading in a Safari iOS or webkit iOS browser, permission is asked for, and on callback I have access to the device's orientation.

HOWEVER, Typescript no like.

Typescript is giving me this error:

Property 'requestPermission' does not exist on type '{ new (type: string, eventInitDict?: DeviceOrientationEventInit | undefined): DeviceOrientationEvent; prototype: DeviceOrientationEvent; }'.

When I fix the error as best to my Typescript knowledge, the code no longer works.

So ... I went about declaring an interface as:

declare interface DeviceOrientationEvent {
  webkitCompassHeading: number | null
  webkitCompassAccuracy: number | null
  requestPermission: () => Promise<PermissionState>
}

enum PermissionState {
  "granted",
  "denied",
}

But, typescript is still not liking things.

Can anyone advise me on what I have done wrong, how to make this work on Safari and also allow me and Typescript to remain best buddies?

1

There are 1 best solutions below

1
Marcos Ocasio On

Ran into this same issue today when compiling our ReactJS application with VS Code. To get around the method missing in TypeScript I just casted the DeviceOrientationEvent to any for that one line.

const setDeviceOrientationPermission = async () => {
  if (typeof (DeviceOrientationEvent as any).requestPermission === 'function') {
    deviceOrientationPermissionState.value = await (DeviceOrientationEvent as any).requestPermission()
  }
}