【发布时间】: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