5

I am getting Typescript error after switching to Ivy compiler:

[Step 4/5] src/app/app.component.html(1,26): Type 'SafeHtml' is not assignable to type 'string'.

In Angular class there is a member property declared as SafeHtml:

@Component({
  selector: 'app',
  template: `<div [innerHTML]="description"></div>`
})
export class AppComponent {
  description: SafeHtml;

  constructor(private sanitizer: DomSanitizer) {}

  ngOnInit(): void {
    this.description = this.sanitizer.sanitize(SecurityContext.HTML, '<strong>whatever comes from server</strong>');
  }
}

My question is how to convert SafeHtml and SafeUrl to string? Is it just .toString() OK?

Angulars SafeHtml is declared as:

/**
 * Marker interface for a value that's safe to use as HTML.
 *
 * @publicApi
 */
export declare interface SafeHtml extends SafeValue {
}

And [innerHtml] defined in lib.dom.d.ts:

interface InnerHTML {
    innerHTML: string;
}

The innerHtml is type of string, whereas I have SafeHtml.

How to reproduce:

git clone https://github.com/felikf/angular-repro-safe-html.git
npm i
npm run build

enter image description here

Felix
  • 3,999
  • 3
  • 42
  • 66
  • Could you please provide your actual code, and not the one you think is relevant ? Typescript typing errors come from the TS, not the template : the code you have provided is next to useless to help you ... –  Oct 07 '19 at 08:02
  • I think you are wrong - Angular Ivy compiler does stricter typechecking on Angular templates. As mentioned in this article: https://blog.angularindepth.com/type-checking-templates-in-angular-viewengine-and-ivy-77f8536359f5 My issue is, that description is defined as `SafeHtml` whereas `InnerHtml` is defined as `String` in lib.dom.d.ts. – Felix Oct 07 '19 at 08:10
  • Sure, whatever you want. But unless you provide the code, no-one will be able to help you out. –  Oct 07 '19 at 08:13
  • 1
    (Also, as per [ask], you should provide a [mcve], so I guess more code isn't that bad after all !) –  Oct 07 '19 at 08:13
  • @Maryannah you are right. I have added steps to reproduce the issue - please see the question. – Felix Oct 07 '19 at 13:45
  • Is that error coming from a serve command, or a build command ? –  Oct 07 '19 at 13:58
  • Is it comming from `npm run build`. – Felix Oct 07 '19 at 14:36
  • 1
    Ok, either try `description: SafeHtml | string;` or `description: any;` to see ? –  Oct 07 '19 at 14:43
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/200510/discussion-between-felix-and-maryannah). – Felix Oct 07 '19 at 14:51
  • I had the same issue and the fix was "SafeHtml | string" as mentioned by user467 ... although I wonder if it was a fix or a hack? The latter? – greg Dec 24 '21 at 22:50

1 Answers1

2

It seems to be a bug, for now this is the answer: https://github.com/angular/angular/issues/33028

Felix
  • 3,999
  • 3
  • 42
  • 66