typescript - object is possibly 'null'
Try casting:
var video = document.querySelector('#camera-stream')
to:
var video = <HTMLVideoElement>document.querySelector('#camera-stream')
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.
Simon's answer can also be written using as
(preferred by some linters like 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 !
where the error is shown, as below:
this.myRef.current!.value = ''
Note: do this if you're sure about the object