You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过装饰器修改Angular组件属性的TypeScript类型

实现方案

核心原理

TypeScript 4.0及以上版本支持属性装饰器通过返回带类型的TypedPropertyDescriptor对象,直接覆盖被装饰属性的静态类型,不需要额外的类装饰器配合即可实现属性类型修改。

完整修改代码

import { Component, OnInit } from "@angular/core";

function ConvertToBoolean() {
  return <T extends object, K extends keyof T>(target: T, key: K): TypedPropertyDescriptor<boolean> => {
    return {
      get(): boolean {
        return !!this[key as any];
      },
      set(value: unknown) {
        Object.defineProperty(this, key, {
          value,
          writable: true,
          enumerable: true,
          configurable: true
        });
      },
      enumerable: true,
      configurable: true
    };
  };
}

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  @ConvertToBoolean()
  title: boolean = "CodeSandbox";

  ngOnInit() {
    console.log(this.title); // 输出 true
    this.title = false; // 无类型错误
    console.log(this.title); // 输出 false
    this.title = "false"; // 赋值合法
    console.log(this.title); // 输出 true
  }
}

注意说明

  • 被ConvertToBoolean装饰的属性静态类型会被TypeScript自动识别为boolean,读取时永远返回布尔值,赋值时默认支持传入任意类型的值,符合装饰器的设计逻辑
  • 如果需要限制赋值时的输入类型,只需修改set方法的参数类型即可,比如要限制仅能传入string | boolean,就把set(value: unknown)改为set(value: string | boolean)
  • Angular项目默认已开启experimentalDecorators配置,无需额外修改TS配置即可生效

内容的提问来源于stack exchange,提问作者kstepien

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 07:57:03