实现陀螺仪权限请求,但我在 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; }'.
在这个问题上有点挣扎。我尝试像这样转换请求权限(DeviceMotionEvent.requestPermission() as any),但它保持不变。由于它不是一个模块,我不能只执行yarn add @types/...
请尽量避免将类型转换为any
,因为它不好,而是尝试缩小类型。
扩展原生 Web APIDeviceOrientationEvent https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEventiOS 设备的事件:
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
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)