typescript - 对象可能是'null'

paa*_*aan 6 typescript angular

我得到以下错误,但程序运行完美

错误

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);
            }
        );

    }
Run Code Online (Sandbox Code Playgroud)

示例错误

在这个问题中尝试了解决方案,但对我没有用.

这个错误的正确解决方法是什么?

Alu*_*dad 15

TypeScript具有处理此方案的特殊语法.

当您知道该值实际上既不是,null也不undefined是编译器没有时,您可以使用非null断言运算符!来进行通信.这适用于基于表达式的表达式.

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
Run Code Online (Sandbox Code Playgroud)

然而,我们更有可能无法明确地知道有问题的对象既不是也不nullundefined,毕竟,这种可能性是故意写下来的类型.在这种情况下,使用!语法会抑制编译时错误,但可能导致运行时失败.在这种情况下,我们应该通过在解除引用之前确保对象是真实的来处理这种可能性.编写此代码的常用习惯用法是

if (video) {
  video.member
}
Run Code Online (Sandbox Code Playgroud)

实际上,TypeScript使用称为控制流分析的上下文类型检查技术,从而确定video可以在if语句块中安全地解除引用.因此,上面的代码不会导致任何错误,因为TypeScript知道它是安全的.

最好!谨慎使用语法.

  • 是的..那时候还没有标准化。只是想让未来的读者知道:-) (2认同)

Sim*_*mon 9

尝试投射:

var video = document.querySelector('#camera-stream')
Run Code Online (Sandbox Code Playgroud)

至:

var video = <HTMLVideoElement>document.querySelector('#camera-stream')
Run Code Online (Sandbox Code Playgroud)


小智 8

西蒙的答案也可以使用as(首选一些像airbnb这样的短绒):

var video = document.querySelector('#camera-stream') as HTMLVideoElement;
Run Code Online (Sandbox Code Playgroud)


Ale*_*Trn 5

一般情况下,如果要禁用TypeScript中的严格空检查功能,可以使用!显示错误的字符,如下所示:

this.myRef.current!.value = ''
Run Code Online (Sandbox Code Playgroud)

注意:如果您确定对象,请执行此操作