Ala Eddine Menai
Ala Eddine Menai

Reputation: 2880

navigator.getBattery() does not exist on type Navigator

I'm trying a custom React hook called useBattery to access the battery status but TypeScript says that getBattery() does not exist on type Navigator:

enter image description here

Based on the MDN documentation the interface name is BatteryManager but I did not find this interface.

Upvotes: 1

Views: 852

Answers (3)

Peter B
Peter B

Reputation: 24280

Because this is not standardized, and also not supported by all browsers, the Typescript team decided that it should not be implemented.

For background see here: https://github.com/microsoft/TypeScript/issues/15314

You can probably get around this by casting navigator to any and then calling the required functions, but you'll have to make it robust in case the browser does not support it.

Upvotes: 2

Harry Hsu
Harry Hsu

Reputation: 408

Looks like the getBattery is not part of the TS Navigator interface, it is likely due to it not being a browser standard.

You may try the following to execute the function anyway tho you might still get some warning

type NavigatorKey = keyof typeof navigator;
const key = 'getBattery' as NavigatorKey;
console.log(await navigator[key]())

Upvotes: 0

PassingThru
PassingThru

Reputation: 34

This works for me in plain vanilla JS...

var Bat=[];

navigator.getBattery().then(function(battery){

 if(isNaN(battery.level)){Bat[0]='?';} else {Bat[0]=battery.level;}

 Bat[1]=battery.charging;

 Bat[2]=battery.chargingTime;

 Bat[3]=battery.dischargingTime;    

});

NB: Array elements 0..3 hold the various values.

Upvotes: 0

Related Questions