【问题标题】:typescript - object is possibly 'null'打字稿 - 对象可能是“空”
【发布时间】:2017-10-12 13:29:27
【问题描述】:

我收到以下错误,但程序运行正常

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

    }

我尝试了in this questions 的解决方案,但对我不起作用。

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

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    尝试投射:

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

    到:

    var video = <HTMLVideoElement>document.querySelector('#camera-stream')
    

    【讨论】:

      【解决方案2】:

      TypeScript 有一个特殊的语法来处理这种情况,non-null assertion operator

      当您知道该值实际上既不是null 也不是undefined 但编译器没有,您可以使用非空断言运算符! 来传达这一点。这在逐个表达式的基础上起作用。

      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
      

      但是,更有可能的是,我们并不确定所讨论的对象既不是 null 也不是 undefined,毕竟,这种可能性是故意编写的类型来传达的。在这种情况下,使用! 语法会抑制编译时错误,但可能会导致运行时失败。在这种情况下,我们应该通过在取消引用之前确保对象是真实的来处理这种可能性。编写此代码的常用习惯用法是

      if (video) {
        video.member
      }
      

      事实上,TypeScript 使用称为 control flow based type analysis 的上下文类型检查技术,从而确定 video 可以在 if 语句块中安全地取消引用,因为 nullundefined 类型已从通过真实检查工会。因此,上面的代码不会导致任何错误,因为 TypeScript 知道它是安全的。

      最好谨慎使用! 语法。

      【讨论】:

      • 使用新的可选链运算符 (?.) 也可以做到这一点
      • 确实如此,但在我写答案的时候还不确定。
      • 是的..那些日子还没有标准化。只是想让未来的读者知道:-)
      【解决方案3】:

      一般情况下,如果要禁用TypeScript中严格的空值检查功能,可以在出现错误的地方使用字符!,如下:

      this.myRef.current!.value = ''
      

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

      【讨论】:

      • 这个答案与两年前写的最受欢迎的答案有什么不同? -1
      【解决方案4】:

      Simon 的答案也可以使用as 来编写(一些像airbnb 这样的短绒工具更喜欢):

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

      【讨论】:

        猜你喜欢
        • 2022-01-26
        • 1970-01-01
        • 2021-12-01
        • 2021-09-27
        • 1970-01-01
        • 2020-11-07
        • 2020-04-25
        • 2021-08-09
        • 2019-07-30
        相关资源
        最近更新 更多