如何在TypeScript中检查SafeHtml的typeof/instanceof类型?
如何检查变量是否为SafeHtml类型?
我有一个类型为string | SafeHtml的变量,需要编写方法判断参数类型并执行对应操作。尝试instanceof和typeof均无法识别SafeHtml类型:
typeof仅支持string、number等基础类型;instanceof SafeHtml无效,因为SafeHtml是TypeScript类型,编译后会被擦除,无法作为运行时值使用。
代码示例:
public isSafeHtml(value: string | SafeHtml) { if (typeof value === 'string' || value instanceof String) { // ..string类型的处理逻辑 } if (typeof value === 'SafeHtml' // 无效 || value instanceof SafeHtml) // 无效 { // ..SafeHtml类型的处理逻辑 } }
解决方法
1. 利用Angular安全类型的内置标识
Angular的SafeHtml实例会携带一个内部属性changingThisBreaksApplicationSecurity,可以通过这个属性判断类型:
import { SafeHtml } from '@angular/platform-browser'; public isSafeHtml(value: string | SafeHtml): boolean { if (typeof value === 'string') { // 处理string类型逻辑 return false; } return typeof value === 'object' && 'changingThisBreaksApplicationSecurity' in value; }
2. 编写TypeScript类型守卫
自定义类型守卫可以让编译器自动识别类型判断结果,提升代码类型安全性:
import { SafeHtml } from '@angular/platform-browser'; function isSafeHtml(value: string | SafeHtml): value is SafeHtml { return typeof value === 'object' && 'changingThisBreaksApplicationSecurity' in value; } // 使用示例 public processValue(value: string | SafeHtml) { if (typeof value === 'string') { // 字符串处理逻辑 } else if (isSafeHtml(value)) { // 编译器自动推断value为SafeHtml类型,可直接调用对应操作 } }
3. 自定义标识属性(可选)
如果是你自己创建的SafeHtml实例,可以手动添加标识属性,增强判断的可读性:
import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; // 创建SafeHtml时附加自定义标识 const safeContent = this.sanitizer.bypassSecurityTrustHtml('<p>示例内容</p>') as SafeHtml & { isSafeHtml: boolean }; safeContent.isSafeHtml = true; // 判断时检查标识 public isSafeHtml(value: string | (SafeHtml & { isSafeHtml: boolean })): boolean { return typeof value === 'object' && value.isSafeHtml; }
内容的提问来源于stack exchange,提问作者MojioMS
相关产品推荐
相关产品推荐

