0

This is my example and it works using an alias. example below: 'aliasCatch'

Passes typescript validation

export type TProcessResponseFunc = (error: TError, stdout: TSTDOut, stderr: TSTDOut) => void;

export interface IObjCMD {
  msg?: string;
  cmd?: string;
  func?: (fn: TProcessResponseFunc) => void;
  catch?: IObjCMD[];
}

const shallowCloneArrObjCMD = (arrNext: IObjCMD[]) => 
  arrNext.reduce((accum, current) => {
    let objCMD: IObjCMD = current;
    if (current.catch) {
      const { ...rest, catch: aliasCatch} = current;
      const arrCatch: IObjCMD[] = aliasCatch ? shallowCloneArrObjCMD(aliasCatch) : [];
      objCMD = { ...rest, catch: arrCatch};
    }
    accum.push({ ...objCMD });
    return accum;
  }, [] as IObjCMD[]);

If I replace the alias to access the destructured item directly - ie catch, in example below, then I get errors all over the place:

Fails typescript validation

const shallowCloneArrObjCMD = (arrNext: IObjCMD[]) => 
  arrNext.reduce((accum, current) => {
    let objCMD: IObjCMD = current;
    if (current.catch) {
      const { ...rest, catch } = current;
      const arrCatch: IObjCMD[] = catch ? shallowCloneArrObjCMD(catch) : [];
      objCMD = { ...rest, catch};
    }
    accum.push({ ...objCMD });
    return accum;
  }, [] as IObjCMD[]);

const { ...rest, catch } = current; - gives me error on the end curly brace: expected : and this breaks the rest of the code.

The only thing I can think what is causing this is because my variable 'catch' might be undefined, as declared in my interface. So making it an alias is bypassing the immediate need for the variable to have value by assigning it to a variable/aka alias.

Some clarification on this would be helpful. Thanks

Steve Tomlin
  • 3,391
  • 3
  • 31
  • 63
  • 1
    `catch` is a reserve keyword that is used with try/catch on with promises. You can't use any reserved keyword as indepent variable, just imagine using a variable called `if`, `else`, `for`, etc.. – gbalduzzi Sep 22 '20 at 15:51

1 Answers1

0

catch is a reserved word. You can't use it as a variable name. current.catch is fine, but const { ...rest, catch } = current isn't.

I recommend avoiding catch (and other reserved words like delete or class) as a property name altogether. If you can't, you may need to use comments to tell your linter not to insist on destructuring:

/* eslint-disable prefer-destructuring */
const arrCatch: IObjCMD[] = current.catch
  ? shallowCloneArrObjCMD(current.catch)
  : [];
objCMD = { ...current };
Chris
  • 6,805
  • 3
  • 35
  • 50