typescript - object is possibly 'null' typescript - object is possibly 'null' typescript typescript

typescript - object is possibly 'null'


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); // errorvideo!.src = window.URL.createObjectURL(stream); // OKvideo.autoplay = true; // error as the `!` does not percolate forwardvideo!.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.


Try casting:

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

to:

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


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

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