Narcil
Narcil

Reputation: 355

DeviceMotionEvent Request Permission with Typescript

Implementing a gyroscope permission request, but i get a typescript error on requestPermission

My code:

if (typeof (DeviceMotionEvent) !== 'undefined' && typeof (DeviceMotionEvent.requestPermission) === 'function') {
        return DeviceMotionEvent.requestPermission()
            .then((response: string) => response === 'granted');
}
TS2339: Property 'requestPermission' does not exist on type '{ new (type: string, eventInitDict?: 
DeviceMotionEventInit): DeviceMotionEvent; prototype: DeviceMotionEvent; }'.

Struggling a bit with this one. i tried casting request permission like this (DeviceMotionEvent.requestPermission() as any) but it stays the same. Since it's not a module i cannot just do yarn add @types/...

Upvotes: 12

Views: 3258

Answers (2)

marko424
marko424

Reputation: 5356

Please try to avoid casting types to any, since its bad and instead try to narrow the type.

Extend native Web API DeviceOrientationEvent event for iOS devices:

interface DeviceOrientationEventiOS extends DeviceOrientationEvent {
  requestPermission?: () => Promise<'granted' | 'denied'>;
}

const requestPermission = (DeviceOrientationEvent as unknown as DeviceOrientationEventiOS).requestPermission;
const iOS = typeof requestPermission === 'function';
if (iOS) {
    const response = await requestPermission();
    if (response === 'granted') {
      // execute
    }
}

Upvotes: 8

Andre Trigo
Andre Trigo

Reputation: 57

You need to cast the Object, not the function, try this:

(DeviceMotionEvent as any).requestPermission() 

Upvotes: 3

Related Questions