-1

Is there a way to "unwrap" variables returned by reload method?

let reloadProps: ReloadProps | undefined;

if (useClientSide() === true) {
    reloadProps = reload(props.eventId);
}

const {
    isTiketAdmin,
    jwt,
    userFbId,
    organizationId,
    organization,
    event,
    enableSaleSwitch,
    enableSaleSwitchOnWordpress,
    permission,
} = reloadProps;

Now I got this error:

./pages/[lang]/event/[...eventId].tsx:72:5
Type error: Property 'isTiketAdmin' does not exist on type 'ReloadProps | undefined'.

  70 |   }
  71 |   const {
> 72 |     isTiketAdmin,
     |     ^
  73 |     jwt,
  74 |     userFbId,
  75 |     organizationId,
error Command failed with exit code 1.
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
János
  • 32,867
  • 38
  • 193
  • 353
  • `if (reloadProps) { ... }`? Right now that will clearly fail if `useClientSide` returns false, for example. If reload always returns an object in the client-side case, why use reloadProps at all, for that matter; just do `if (useClientSide()) { const { isTiketAdmin, ... } = reload(props.eventId); ... }`. – jonrsharpe Aug 08 '21 at 07:21
  • Why not to wrap it inside a promise? – RegarBoy Aug 09 '21 at 11:50

1 Answers1

0

The main problem is, that the values you want to get out of reloadProps are not available if is undefined. You have to check that the value is not undefined beforehand:

if (reloadProps !== undefined) {
  const {
    isTiketAdmin,
    jwt,
    userFbId,
    organizationId,
    organization,
    event,
    enableSaleSwitch,
    enableSaleSwitchOnWordpress,
    permission,
  } = reloadProps;
}

This way the compiler can infer, that the type is not ReloadProps | undefined anymore but ReloadProps only and then you can access the values.

Peter Lehnhardt
  • 4,375
  • 1
  • 14
  • 33