Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript - object is possibly 'null'

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?

like image 907
paan Avatar asked May 13 '17 08:05

paan


1 Answers

TypeScript has a special syntax for handling this scenario, the non-null assertion operator.

When you know the value is actually neither null nor undefined but the compiler does not, you can use the non-null assertion operator, !, to communicate this. This works on an expression by expression basis.

declare let video: HTMLVideoElement | null | undefined;

video.src = window.URL.createObjectURL(stream); // error

video!.src = window.URL.createObjectURL(stream); // OK

video.autoplay = true; // error as the `!` does not percolate forward

video!.autoplay = true; // OK

However, it is far more likely that we do not definitively know that the object in question is neither null nor undefined and, after all, that possibility is what the type was deliberately written to convey. In such a case, using the ! syntax would suppress a compile time error but could result in a runtime failure. In this case we should rather handle the possibility by ensuring that the object is truthy before dereferencing it. A common idiom for writing this code is

if (video) {
  video.member
}

In fact, TypeScript uses a contextual type checking technique known as control flow based type analysis and thereby determines that video can safely be dereferenced in the if statement block because the null and undefined types have be removed from the union by truthy check. Therefore, the above code does not result in any errors because TypeScript knows that it is safe.

It is best to use the ! syntax very sparingly.

like image 157
Aluan Haddad Avatar answered Oct 03 '22 20:10

Aluan Haddad