Home > Software design >  how to give object class to the function
how to give object class to the function

Time:09-24

Here is the code enter image description here

copy-pasted code:

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);
        }
      }

How can I add any object class to the function? It gives 'Entity' only refers to a type, but is being used as a value here.

CodePudding user response:

Since all types are erased after compilation, and so are type parameters (<Entity>), there's no such thing as Entity at runtime, so you cannot use it anywhere but in type annotations.

You need to pass it as a value to your function, like this:

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

I can't figure out a type for Entity parameter, because I cannot really tell what it is and how it's used from your example, but you can look for constructs like typeof MyClass to pass a class itself as a parameter, or { new(): MyClassInstance } for just something that can be called with new keyword. I've made some examples here.

CodePudding user response:

There is needed to add EntityTarget to implement any Entity class, it looks like:

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

So the using would be

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