【问题标题】:How to change type of property via docorators如何通过医生更改属性类型
【发布时间】:2021-10-19 17:25:50
【问题描述】:

我有一个像这样的角度组件:

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

function ConvertToBoolean<T extends object, K extends keyof T>() {
  return (target: Object, key: string): void => {
    Object.defineProperty(target, key, {
      set(this: T, initialValue: T[K] | K) {
        let currentValue = initialValue;

        Object.defineProperty(this, key, {
          get(): boolean {
            return !!currentValue;
          },
          set(this: T, value: T[K]) {
            currentValue = value;
          }
        });
      }
    });
  };
}

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

  ngOnInit() {
    console.log(this.title);
    this.title = false; // error
    this.title = "false"; // pass
  }
}

如您所见,ConvertToBoolean 装饰器将任何属性更改为布尔值。 但我想在 AppComponent 类中将title 的类型从string 更改为boolean,但我不知道这是可能的。

在此代码中,我收到一个错误:

你能告诉我怎么做吗?或者有没有关于是否有可能获得它的信息?

我在谷歌上没有找到任何关于它的信息。我只找到了一个类装饰器来更改构造函数属性的类型,但这并不能解决我的问题。

您也可以在this demo in codesandbox 上查看我的代码。

【问题讨论】:

  • 你几乎肯定不能这样做,因为装饰器在运行时运行,但类型分析发生在编译时。但实际上你真的不想要这个。它违反了最小意外原则:现在寻找类型的地方不是 1 个地方,而是有 n 个地方。它几乎肯定会在 JIT 中触发性能下降的 deopts。它违反了域名的语义,为什么“标题”是布尔值?等等等等。这只是个坏主意。
  • microsoft/TypeScript#4881;这是一个很长的讨论,但基本上不,TypeScript 不允许您使用属性装饰器执行此操作。 TS 的人是probably not going to touch decorators until their JS proposal stabilizes,所以事情暂时停滞不前。不确定是否有任何你觉得合适的解决方法。

标签: angular typescript decorator typescript-decorator angular-decorator


【解决方案1】:

我们可以更简单...

用两种类型定义你的变量:

let variable:boolean | string;

在打字稿操场上检查它。:https://www.typescriptlang.org/play?#code/DYUwLgBAbghgTgSxgI1ALmQe06GA7CAHwgGcxE8BzAbgChbZEVQIBeCcgVxDsaVRBsIAIjAgyw3vH4t2ARjl0gA

【讨论】:

  • 我知道我可以这样解决。在我的项目中,使用装饰器来更改整个类型而不是添加另一个更合适。不过谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
相关资源
最近更新 更多