Type 'string | null' is not assignable to type 'string' error with iFrame

yotube
0

Issue

I am trying to print a pdf file with angular but I am having an error on 'iframe.src' line- This is the error: Type 'string | null' is not assignable to type 'string'.

    this.myService.printPages(shareFilter)
.subscribe((result: any) => {

const pdf = new Blob([result], { type: 'application/pdf' });
const blobUrl = URL.createObjectURL(pdf);
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = this.sanitizer.sanitize(SecurityContext.RESOURCE_URL, this.sanitizer.bypassSecurityTrustResourceUrl(blobUrl));
document.body.appendChild(iframe);
iframe.contentWindow.print();
}
)

Solution

(Assuming this.sanitizer is an instance of DomSantitizer) this.sanitizer.sanitize() has as return type string | null, i.e. may return a string or null. Whereas iframe.src expects a string to be assigned.

With strictNullChecks enabled in your tsconfig.json this will cause the error you're experiencing because you're trying to assign a (return) value that could possibly be null to a property that must be a string.

To address this error you must ensure that the value you're assigning to iframe.src is not null, e.g. by checking it before and assigning a default value in case it is null.

A nice shorthand for such a check is the nullish coalescing operator (??):

const url = this.sanitizer.sanitize(SecurityContext.RESOURCE_URL, this.sanitizer.bypassSecurityTrustResourceUrl(blobUrl));
iframe.src = url ?? '';

For readability the return value of this.sanitizer.sanitize() is first assigned to url which may be a string or null. The expression url ?? '' will evaluate to url if it is a string/not null and to the empty string ('') in case it is null.



Answered By - acran
Tags

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
To Top