据我所知,答案可能是“否”。装饰器目前不改变类型,因此类型系统不会注意到装饰方法和未装饰方法之间的区别。人们已经要求为类装饰器提供类似的东西(而不是像你正在使用的方法装饰器),here... 但这是一个有争议的问题。有些人非常强烈地认为装饰器不应该被类型系统观察到,而另一些人则同样强烈地认为不同。在 JavaScript 中的装饰器最终确定之前,TypeScript 的维护者不太可能对它们的工作方式进行任何更改,因此我不希望这里有任何立即解决方案。
但是,如果我们备份并尝试提出一个与应用这些装饰器具有相同效果的解决方案,同时跟踪文件系统中发生的事情呢?
为了得到一些具体的东西,我要让test() 做一些事情:
function test(
target: any,
propertyKey: string,
descriptor: PropertyDescriptor
) {
console.log(
"decorated test on target",
target,
"propertyKey",
propertyKey,
"descriptor",
descriptor
);
}
当你像这样制作A 时:
class A {
@test
public x() {}
public y() {}
}
你会得到以下日志:decorated test on target Object { … } propertyKey x descriptor Object { value: x(), writable: true, enumerable: false, configurable: true }
由于我们无法检测何时应用了装饰器,如果我们根本不使用@test 装饰样式,而是在属性描述符上调用实际的test 函数,这就是装饰器的方法编译到反正?如果我们创建自己的 apply-instance-method-decorator 函数,我们可以让该函数同时进行装饰 并且 跟踪类型系统中装饰了哪些方法。像这样的:
function decorateInstanceMethods<T, K extends Extract<keyof T, string>>(
ctor: new (...args: any) => T,
decorator: (
target: any,
propertyKey: string,
descriptor: PropertyDescriptor
) => void,
...methodsToDecorate: K[]
): T & { decoratedMethods: K[] } {
methodsToDecorate.forEach(m =>
decorator(
ctor.prototype,
m,
Object.getOwnPropertyDescriptor(ctor.prototype, m)!
)
);
return Object.assign(ctor.prototype, {
decoratedMethods: methodsToDecorate
});
}
该函数可以隐藏在某个库中。下面是你如何制作A 并用test 装饰它:
class A {
public x() {}
public y() {}
}
const DecoratedAPrototype = decorateInstanceMethods(A, test, "x");
这最终会记录与以前相同的内容:decorated test on target Object { … } propertyKey x descriptor Object { value: x(), writable: true, enumerable: false, configurable: true }
但是现在,DecoratedAPrototype 是 A.prototype 加上一个 decoratedMethods 属性,其类型是 Array<"x">,所以你可以这样做:
type DecoratedOnly<
T extends {
decoratedMethods: (keyof T)[];
}
> = Pick<T, T["decoratedMethods"][number]>;
const a: DecoratedOnly<typeof DecoratedAPrototype> = new A();
a.x(); // okay
a.y(); // error, property "y" does not exist on DecoratedOnly<typeof DecoratedAPrototype>
您可以看到A 类型仍然不知道装饰了哪些方法,但DecoratedAPrototype 知道。这足以为您提供您正在寻找的行为(我使用了Pick,所以省略的属性只是不知道存在并且没有明确地never...我猜这不是超级重要)
这对你有用吗?是的,它比仅仅使用装饰器要复杂一些,但它是我能得到的最接近你想要的东西。
无论如何,希望对您有所帮助。祝你好运!
Link to code