问题描述
我在TypeScript中有一个属性装饰器,该装饰器仅可用于 Array
类型的属性。要强制执行此操作,如果属性类型不是 Array
(使用以获取属性类型信息):
I have a property decorator in TypeScript that is only usable on properties of type Array
. To enforce this, a TypeError
is thrown at runtime if the property type is not Array
(using reflect metadata to get property type information):
function ArrayLog(target: any, propertyKey: string) {
if (Reflect.getMetadata("design:type", target, propertyKey) !== Array) {
throw new TypeError();
}
// ...
}
但是,我认为这对开发人员不太友好。我如何才能使TypeScript编译器允许在具有特定类型的属性上仅使用特定的属性装饰器 ?
However, I wouldn't consider this too dev-friendly. How could I make it so that the TypeScript compiler allows using a certain property decorator only on properties with a certain type?
推荐答案
有一个技巧可以实现此目的:
There is a little trick to achieve this:
function ArrayLog<K extends string, C extends { [ A in K ]: Array<any> }>(target: C, key: K) {
/* ... */
}
甚至更好(请参见):
function ArrayLog<K extends string, C extends Record<K, Array<any>>>(target: C, key: K) {
/* ... */
}
不幸的是,这仅适用于公共财产,不适用于私人或受保护财产...
Unfortunately this only works for public properties, not for private or protected properties...
这篇关于仅用于特定属性类型的属性装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!