Home > Back-end >  Changing type from entity when passing as parameter
Changing type from entity when passing as parameter

Time:11-06

I'm attempting to change the type of the Entity. I'm calling a function with requires 2 parameters, 1 is the entity and the other is a location. Although when I attempt to pass a Type for the first entity is gives me this error:

Argument of type 'Node<EntityBasic>' is not assignable to parameter of type 'Node<AlertBasic>'.
  Type 'EntityBasic' is not assignable to type 'AlertBasic'.
    Property 'id' is optional in type 'EntityBasic' but required in type 'AlertBasic'.

This is the function:

public async func() {
 const entBasic: EntityBasic = this.getEntity(entity);
 const NEO4J_TYPE = entType === 'alert' ? 'Alert' : 'Guide';

 const entNode = await this.neo4jService.createOrUpdate<EntityBasic>(
      NEO4J_TYPE,
      entBasic.id,
      entBasic,
    );

 if (NEO4J_TYPE === 'Alert')
      await this.calendarEventsSyncService.handleEvents(entNode, location); 
}

I need to change the entNode from EntityBasic to AlertBasic
I have attempted to:

if (NEO4J_TYPE === 'Alert')
      await this.calendarEventsSyncService.handleEvents(entNode: AlertBasic, location);

But I get a Expected 2 parameter instead of 3

CodePudding user response:

You can cast entNode to Node<AlertBasic>:

 await this.calendarEventsSyncService.handleEvents(entNode as Node<AlertBasic>, location);

or in case of interface confict between AlertBasic and EntityBasic:

 await this.calendarEventsSyncService.handleEvents(entNode as unknown as Node<AlertBasic>, location);

CodePudding user response:

As far as I know you can only use entNode: AlertBasic to declare a function signature. Not when calling a function, which is what you are doing.

if (NEO4J_TYPE === 'Alert')
      await this.calendarEventsSyncService.handleEvents(entNode: AlertBasic, location);

There are several ways to handle this and which is appropriate really depends on the larger system.

A risky solution: use as

You can use as to tell TypeScript to pretend one type to be another. This could lead to issues, since you are introducing a lie into your system.

if (NEO4J_TYPE === 'Alert')
      await this.calendarEventsSyncService.handleEvents(entNode as Node<AlertBasic>, location);

transform the type beforehand

You may want to transform one type to another using a function. With a signature like:

function transform_AlertBasic_toEntityBasic( alert_basic: AlertBasic ): EntityBasic {
   // ... some code that makes the transformation
}

check if there is a supertype

There may be a superclass that covers an API for both types you can use.

  • Related