typescript 打字稿 - 对象可能是“空”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43951090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:32:55  来源:igfitidea点击:

typescript - object is possibly 'null'

angulartypescript

提问by paan

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 questionsbut didn't work for me.

在这个问题中尝试了解决方案但对我不起作用。

What is the proper fix for this error?

此错误的正确修复方法是什么?

采纳答案by Simon

Try casting:

尝试铸造:

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

to:

到:

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

回答by Aluan Haddad

TypeScript has a special syntax for handling this scenario.

TypeScript 有一种特殊的语法来处理这种情况。

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

当您知道该值实际上既不是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

However, it is far more likely that we do not definitively know that the object in question is neither nullnor undefinedand, 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

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

if (video) {
  video.member
}

In fact, TypeScript uses a contextual type checking technique known as control flow analysis and thereby determines that videocan safely be dereferenced in the ifstatement block. Therefore, the above code does not result in any errors because TypeScript knows that it is safe.

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

It is best to use the !syntax very sparingly.

最好!非常谨慎地使用该语法。

回答by Alex Trn

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

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

this.myRef.current!.value = ''

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

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

回答by wfreude

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

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

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