【发布时间】:2020-04-25 14:39:22
【问题描述】:
我正在尝试实现我自己的 ORM,我在 TypeScript 中发现了一些我不明白的有趣的东西。也许你们中的一个可以向我解释一下,或者它可能是一个打字稿错误。
这是简化的基本结构,这里也有这种现象。
我们有一个属性装饰器,它接受一个类类型的参数。
// This is not required, only used to define the entityClass type more explicite
export abstract class Entity { }
export function Decorator(entityClass: typeof Entity) {
return function(target: any, propertyName: string) {
console.log(entityClass);
}
}
A 类文件: EntityA.ts
import { Entity, Decorator } from "./index";
import { EntityB } from "./EntityB";
export class EntityA extends Entity {
@Decorator(EntityB)
public propertyA: any;
}
B 类文件: EntityB.ts
import { Entity, Decorator } from "./index";
import { EntityA } from "./EntityA";
export class EntityB extends Entity {
@Decorator(EntityA)
public propertyB: any;
}
触发打字稿使用装饰器输出console.log的一点代码:
运行.ts
import { EntityA } from "./EntityA";
import { EntityB } from "./EntityB";
const objA = new EntityA();
const objB = new EntityB();
运行这个脚本我得到:
undefined
[Function: EntityB]
这个undefined就是这个现象。
现在我在 EntityA.ts 中删除这一行 @Decorator(EntityB) 并再次运行脚本,undefine 消失了。相反,我得到了预期的输出:
[Function: EntityA]
我是不是对装饰器有误解,或者这是一个打字稿错误?
【问题讨论】:
标签: typescript decorator