'Property 'wakeLock' does not exist on type 'Navigator'
I need to use the Screen Wake Lock API in my angular app
here is my code
if ('wakeLock' in navigator) {
await navigator.wakeLock.request();
}
However, Angular compilation fails with the following error:
Error: src/app/feature/test/test/test.component.ts:20:42 - error TS2339: Property 'wakeLock' does not exist on type 'Navigator'.
Angular version and information
_ _ ____ _ ___
/ \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|
/ △ \ | '_ \ / _` | | | | |/ _` | '__| | | | | | |
/ ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | |
/_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___|
|___/
Angular CLI: 13.0.3
Node: 16.13.0
Package Manager: npm 8.1.0
OS: win32 x64
Angular: 13.0.2
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... platform-server, router
Package Version
---------------------------------------------------------
@angular-devkit/architect 0.1300.3
@angular-devkit/build-angular 13.0.3
@angular-devkit/core 13.0.3
@angular-devkit/schematics 13.0.3
@angular/cdk 13.0.3
@angular/cli 13.0.3
@angular/flex-layout 13.0.0-beta.36
@angular/material 13.0.3
@schematics/angular 13.0.3
rxjs 6.6.7
typescript 4.4.4
How can fix typescript to contain Screen Wake Lock API and can compile codes?
Solution 1:[1]
Finally, after two weeks I found a way that supports this by adding the DefinitelyTyped. Two-step can fix this.
- Install the
@types/dom-screen-wake-lockpackage
npm i @types/dom-screen-wake-lock -D
- After installing the package you must add types to
tsconfig.jsonlike this
{
...
"compilerOptions":{
...
"types":[
...
"dom-screen-wake-lock"
...
]
...
}
...
}
Solution 2:[2]
This is what I did to make it work:
const anyNav: any = navigator
if ('wakeLock' in navigator) {
anyNav["wakeLock"].request("screen")
}
I first tried adding the DefinitelyTyped definition which fixed the editor throwing errors, but it was still causing compilation to fail. This did the trick, basically we are saving the navigator to an any type variable which allows us to call any properties or methods without type checking.
The if statement allows for checking that wakelock is supported by the browser before trying to call it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | behroozbc |
| Solution 2 | Kyle Gibbons |
