Home » vue » type script : window.open().document.write() is 'possible null '

type script : window.open().document.write() is 'possible null '

Posted by: admin November 26, 2021 Leave a comment


I am coding in Vue and Typescript

I have this code in my Vue component

const WinPrint = window.open(.,.,.) 

WinPrint.document.write(`<!DOCTYPE html> ....`)

but I have this error

enter image description here

how can i fix this problem ?


window.open can return null in some cases. By the error you mention, TypeScript is warning you that you might be accessing some properties of null there. You need to check for the null case in your code. Something like

const WinPrint = window.open(.,.,.);

if (!WinPrint) {
    // handle the case when the window could not be opened here
} else {
    WinPrint.document.write(`<!DOCTYPE html> ....`)

This will make the TypeScript see that the WinPrint is defined in the else branch.