3

I wonder if it is possible to cast object parameter passed from LWC Component to specific instance of Wrapper class. In Example we have WrapperB that extends WrapperA and we want to cast data passed to apex from LWC.

Apex code:

public with sharing class MyController {
    @AuraEnabled(Cacheable=true)
    public static String getByValue(WrapperA wrpA) {
       WrapperB wrpB = (WrapperB) wrpA; // TypeError
    }

    public class WrapperA {
       @AuraEnabled
       public String valueA {get; set;}
    }

    public class WrapperB extends WrapperA {
       @AuraEnabled
       public String valueB {get; set;}
    }
}

LWC component:

import { LightningElement, wire } from "lwc";
import getByValue from "@salesforce/apex/MyController.getByValue";

export default class MyComponent extends LightningElement {

   wrp = { valueB : 'Value B' }

   @wire(getByValue, {wrpA : "$wrp"})
   wiredValue(result) {
      if (result.data) {
         ...
      } else if (result.error) {
         ...
      }
   }
}

Parameter passed from LWC component as JSON object to apex are deserialized to Map<any, any>? Is it possible to cast it to specific wrapper class?

1 Answer 1

4

The runtime will deserialize only to the known type (the type you specify for the parameter), not any specific subtype, as it has no way of knowing which subtype you meant; there's no attribute or property you can set to inform the runtime aside from the parameter's data type. You'd have to serialize the object to JSON on the client side, then deserialize on the server side. To actually use it, then, you'd still have to cast it to a concrete type.

Something like this:

let param = { valueB: 'Something' };
myApexMethod({ param: JSON.stringify(param), paramType: 'myApexClass.WrapperB' });

@AuraEnabled(cacheable=true) public static WrapperB myApexMethod(String param, String paramType) {
  Object wrappedObject = JSON.deserialize(param, Type.forName(paramType));
  if(wrappedObject instanceOf WrapperB) {
    WrapperB wrpB = (WrapperB)wrappedObject;
    return wrpB;
  }
  if(wrappedObject instanceOf WrapperA) {
    // Do something about that here //
  }
  // etc
  return null;
}

This is all because the type system doesn't have any way to provide any other "hints" except for the parameter's type itself, so you end up having to do extra work. Whatever it is you're trying to do, it's probably easier to either write separate methods, or squish WrapperB and WrapperA into the same object and simply use it that way.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .