简体   繁体   English

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

[英]typescript - object is possibly 'null'

I get this error for the following but the program running perfectly我收到以下错误,但程序运行完美

错误

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

    }

示例错误

I tried the solution in this questions but didn't work for me.在这个问题中尝试了解决方案但对我不起作用。

What is the proper fix for this error?此错误的正确修复方法是什么?

TypeScript has a special syntax for handling this scenario, the non-null assertion operator . TypeScript 有一种特殊的语法来处理这种情况,即非空断言运算符

When you know the value is actually neither null nor undefined but the compiler does not, you can use the non-null assertion operator, !当您知道该值实际上既不是null也不是undefined但编译器不知道时,您可以使用非空断言运算符! , 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.然而,更有可能的是,我们不能明确地知道所讨论的对象既不是null也不是undefined ,毕竟,这种可能性是故意编写的类型来传达的。 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.事实上,TypeScript 使用一种称为基于控制流的类型分析的上下文类型检查技术,从而确定video可以安全地在if语句块中取消引用,因为nullundefined类型已通过真实检查从联合中删除。 Therefore, the above code does not result in any errors because TypeScript knows that it is safe.因此,上面的代码不会导致任何错误,因为 TypeScript 知道它是安全的。

It is best to use the !最好使用! syntax very sparingly.语法非常谨慎。

Try casting:尝试铸造:

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

to:到:

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

西蒙的答案也可以使用as (首选一些像 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 !一般来说,如果你想禁用 TypeScript 中的严格空检查功能,你可以使用字符! where the error is shown, as below:显示错误的地方,如下所示:

this.myRef.current!.value = ''

Note: do this if you're sure about the object注意:如果您确定对象,请执行此操作

var variableName=<HTMLtagnameElement>document.querySelector('classname or id');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM