使用 Typescript 请求 DeviceMotionEvent 权限

Nar*_*cil 9 javascript typescript reactjs

实现陀螺仪权限请求,但我在 requestPermission 上收到打字稿错误

我的代码:

if (typeof (DeviceMotionEvent) !== 'undefined' && typeof (DeviceMotionEvent.requestPermission) === 'function') {
        return DeviceMotionEvent.requestPermission()
            .then((response: string) => response === 'granted');
}
Run Code Online (Sandbox Code Playgroud)
if (typeof (DeviceMotionEvent) !== 'undefined' && typeof (DeviceMotionEvent.requestPermission) === 'function') {
        return DeviceMotionEvent.requestPermission()
            .then((response: string) => response === 'granted');
}
Run Code Online (Sandbox Code Playgroud)

在这个问题上有点挣扎。我尝试像这样转换请求权限(DeviceMotionEvent.requestPermission() as any),但它保持不变。由于它不是一个模块,我不能只执行yarn add @types/...

mar*_*424 6

请尽量避免将类型转换为any,因为它不好,而是尝试缩小类型。

扩展DeviceOrientationEventiOS 设备的本机 Web API 事件:

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
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 3

您需要转换对象,而不是函数,试试这个:

(DeviceMotionEvent as any).requestPermission() 
Run Code Online (Sandbox Code Playgroud)