typescript - object is possibly 'null'

Viewed 70114

I get this error for the following but the program running perfectly

error

var video = document.querySelector('#camera-stream'),

if(!navigator.getMedia){
        displayErrorMessage("Your browser doesn't have support for the navigator.getUserMedia interface.");
    }
    else{
        // Request the camera.
        navigator.getMedia(
            {
                video: true
            },
            // Success Callback
            function(stream:any){

                // Create an object URL for the video stream and
                // set it as src of our HTLM video element.
                video.src = window.URL.createObjectURL(stream);

                // Play the video element to start the stream.
                video.play();
                video.onplay = function() {
                    showVideo();
                };

            },
            // Error Callback
            function(err:any){
                displayErrorMessage("There was an error with accessing the camera stream: " + err.name, err);
            }
        );

    }

example error

I tried the solution in this questions but didn't work for me.

What is the proper fix for this error?

4 Answers

Simon's answer can also be written using as (preferred by some linters like airbnb):

var video = document.querySelector('#camera-stream') as HTMLVideoElement;

Generally, if you want to disable the strict null checks function in TypeScript, you can use the character ! where the error is shown, as below:

this.myRef.current!.value = ''

Note: do this if you're sure about the object

Related