DEV Community

Discussion on: Enabling Dark Mode On Websites Based On Surrounding Light

Collapse
 
msumanphexaware profile image
MsumanP-hexaware • Edited

I am getting error like Property 'AmbientLightSensor' does not exist on type 'Window' & Cannot find name 'AmbientLightSensor'.

My Code:
if (window.AmbientLightSensor) {
const sensor = new AmbientLightSensor();
sensor.onreading = () => console.log(sensor.illuminance);
sensor.onerror = event => console.log(event.error.name, event.error.message);
sensor.start();
}

Thread Thread
 
ananyaneogi profile image
Ananya Neogi

You need to extend the existing Window interface to tell it about this new property.
So, before your class implementation add this code -

declare global {
    interface Window {
        AmbientLightSensor: any;
    }
}

Then you can add your AmbientLightSensor code in the following way -

        if (window.AmbientLightSensor) {
            const sensor = new window.AmbientLightSensor();
            sensor.onreading = () => console.log(sensor.illuminance);
            sensor.onerror = event => console.log(event.error.name, event.error.message);
            sensor.start();
        }

I hope this will solve your problem.

Thread Thread
 
msumanphexaware profile image
MsumanP-hexaware • Edited

Now error is not coming but window.AmbientLightSensor is coming as undefined.