【问题标题】:how to give object class to the function如何为函数赋予对象类
【发布时间】:2021-09-15 10:43:17
【问题描述】:

这里是代码

复制粘贴代码:

const check = async <Entity>(

      ) => {
        if (ObjectUtil.areChanged(memberUser.client, data, 'employmentTypeId')) {
          const beforeEmploymentType = await manager.findOneOrFail(Entity, memberUser.client.employmentTypeId);
          const afterEmploymentType = await manager.findOneOrFail(EmploymentType, data.employmentTypeId);
        }
      }

如何将任何对象类添加到函数中?它给了'Entity' only refers to a type, but is being used as a value here.

【问题讨论】:

    标签: typescript oop


    【解决方案1】:

    由于所有类型在编译后都会被删除,类型参数 (&lt;Entity&gt;) 也是如此,因此在运行时没有 Entity 这样的东西,所以你不能在任何地方使用它,只能在类型注释中使用。

    您需要将其作为值传递给您的函数,如下所示:

    const check = async (Entity: ???) => { ... }
    

    我无法确定Entity 参数的类型,因为我无法从您的示例中真正分辨出它是什么以及它是如何使用的,但是您可以寻找像typeof MyClass 这样的构造来将类本身作为参数,或 { new(): MyClassInstance } 仅用于可以使用 new 关键字调用的内容。我做了一些例子here

    【讨论】:

      【解决方案2】:

      需要添加EntityTarget来实现任何Entity类,它看起来像:

      const check = async <Entity, A>(
          manager: EntityManager,
          entity: EntityTarget<Entity>,
          base: A,
          key: keyof A,
      ) => {
        const beforeEntity = await manager.findOneOrFail(entity, base[key]);
      };
      

      所以使用会是

      await check(manager, Room, booking, 'roomId');
      

      【讨论】:

        猜你喜欢
        • 2022-12-17
        • 2012-11-24
        • 1970-01-01
        • 2017-11-25
        • 2021-04-14
        • 1970-01-01
        • 1970-01-01
        • 2021-03-17
        • 2012-01-03
        相关资源
        最近更新 更多