在 Typescript 中检查装饰 class 的类型?
Checking for the type of a decorated class in Typescript?
如果我们这样定义装饰器函数:
return function IsDefined(object: any, propertyName: string) {
....
]
然后像这样装饰一些属性:
class Test {
@IsDefined() p1: String = "";
}
并在装饰器中执行这个测试:
expect(object).to.equal(Test);
它应该通过吗?什么是 object
?
这例如通过:
const instance:any = new Test();
expect(object.constructor.name).
to.equal(instance.constructor.name);
属性 装饰器的第一个参数始终是 class 的当前实例或静态成员的构造函数。所以在这种情况下 object
将是 Test
class 调用实例装饰器的来源。
这个测试不应该通过,因为我提到它是当前实例。您可以检查对象是否实际上是 Test
的实例或类似于上一个示例:
expect(object instanceof Test).toBeTruthy();
或
expect(object.constructor.name).toBe('Test');
如果我们这样定义装饰器函数:
return function IsDefined(object: any, propertyName: string) {
....
]
然后像这样装饰一些属性:
class Test {
@IsDefined() p1: String = "";
}
并在装饰器中执行这个测试:
expect(object).to.equal(Test);
它应该通过吗?什么是 object
?
这例如通过:
const instance:any = new Test();
expect(object.constructor.name).
to.equal(instance.constructor.name);
属性 装饰器的第一个参数始终是 class 的当前实例或静态成员的构造函数。所以在这种情况下 object
将是 Test
class 调用实例装饰器的来源。
这个测试不应该通过,因为我提到它是当前实例。您可以检查对象是否实际上是 Test
的实例或类似于上一个示例:
expect(object instanceof Test).toBeTruthy();
或
expect(object.constructor.name).toBe('Test');