【问题标题】:TypeScript decorators phenomenon (decorator parameter becomes undefined in a special case)TypeScript 装饰器现象(装饰器参数在特殊情况下变得未定义)
【发布时间】: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


    【解决方案1】:

    您在代码中有循环引用 - EntityA 依赖于 EntityB,反之亦然。

    EntityA 的初始化过程中,传入@Decorator(EntityB)EntityBundefined,因此装饰器会捕获“未定义”值。

    EntityB 的初始化过程中,EntityA 已经存在,所以一切似乎都正常。

    【讨论】:

      猜你喜欢
      • 2017-06-23
      • 2022-08-15
      • 2020-09-04
      • 2015-10-23
      • 2018-01-31
      • 2013-02-06
      • 2016-06-09
      • 2020-07-11
      • 2021-09-30
      相关资源
      最近更新 更多