3

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?

Micheal J. Roberts
  • 3,735
  • 4
  • 37
  • 76
  • Does this answer your question? [DeviceMotionEvent Request Permission with Typescript](https://stackoverflow.com/questions/60640018/devicemotionevent-request-permission-with-typescript) – marko424 Aug 16 '22 at 06:13

1 Answers1

0

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()
  }
}
  • I suspect this has been down voted because you should really avoid casting as any at all costs. It works, but you loose the very thing you use TS for: type safety. – Micheal J. Roberts Aug 16 '22 at 14:18