TypeScript - Angular 中的可信类型
我正在尝试在 Angular 中启用受信类型。添加 CSP 头没问题,但一旦我尝试添加自定义策略,就会出现以下错误。
如果我查看 MDN,他们说该属性确实存在,但并不是所有浏览器都支持。
✘ [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', {
你可以通过打开 Angular playground 并将测试方法添加到组件中来重现它。
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);
我漏掉了什么?
答案#1
TypeScript 尚未包含 trusted types 的类型定义,因为这是一个目前仅在 Chrome 中可用的功能(正如你在你链接的 MDN 文档中可以看到的)。你可以通过 @types/trusted-types npm 包从 Definitely Typed 安装这些类型定义。
答案#2
这似乎是一个新功能,将来会被添加到 Window 类型中。
这在 MDN 中标记如下。
数量有限
此功能不是基线功能,因为它在一些最常用的浏览器中无法使用。
如果你必须使用它,你必须定义一个自定义类型。
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 演示
最简单的方法就是将 window 标记为 any。
export class App {
name = 'Angular';
public test(): void {
let sanatizer = (window as any).trustedTypes.createPolicy(
'my-policy',
{}
);
}
}
