Search code examples
angulartypescripttrusted-types

Trusted types in Angular


I am trying to enable trusted types in Angular. Adding the CSP header is not a problem but once I try to add a custom policy I get the following error.

If I look at MDN they say the property does exist but is not supported in all browsers.


✘ [ERROR] TS2339: Property 'trustedTypes' does not exist on type 'Window & typeof globalThis'. [plugin angular-compiler]

    src/main.ts:13:29:
      13 │       let sanatizer = window.trustedTypes.createPolicy('my-policy', {

You can reproduce it with opening Angular playground and adding the test method to the component.

import {Component} from '@angular/core';
import {bootstrapApplication} from '@angular/platform-browser';

@Component({
  selector: 'app-root',
  standalone: true,
  template: `
    Hello world!
  `,
})
export class PlaygroundComponent {
  public test() : void {
    let sanatizer = window.trustedTypes.createPolicy('my-policy', {

    ));
  }
}

bootstrapApplication(PlaygroundComponent);

What am I missing?


Solution

  • It seems like a new feature and will be added in the Window type in future.


    This is marked as below in MDN.

    Limited availability

    This feature is not Baseline because it does not work in some of the most widely-used browsers.


    If you must use it, you have to defined a custom type.

    import { Component } from '@angular/core';
    import { bootstrapApplication } from '@angular/platform-browser';
    
    export type WindowExtended = (Window & typeof globalThis & {trustedTypes: any });
    
    @Component({
      selector: 'app-root',
      standalone: true,
      template: `
        <h1>Hello from {{ name }}!</h1>
        <a target="_blank" href="https://angular.dev/overview">
          Learn more about Angular
        </a>
      `,
    })
    export class App {
      name = 'Angular';
      public test() : void {
        let sanatizer = (window as WindowExtended).trustedTypes.createPolicy('my-policy', {
          
        });
      }
    }
    
    bootstrapApplication(App);
    

    Stackblitz Demo


    The simplest way is to just mark window as any.

    export class App {
      name = 'Angular';
      public test(): void {
        let sanatizer = (window as any).trustedTypes.createPolicy(
          'my-policy',
          {}
        );
      }
    }