Typescript Array OR Object

Viewed 183

I have this signature static cleanSOAP(envelope: [] | {}, removePassword: boolean = false) and after a constructor verification, if it's an Array I do a forEach on the envelope but, I got the error: Property 'forEach' does not exist on type '{} | []'. Property 'forEach' does not exist on type '{}'.ts(2339)

How can I prevent that ?

Code:

 static cleanSOAP(envelope: [] | {}, removePassword: boolean = false) {

    const unwantedProperties = ['$attributes'];

    if (removePassword === true) unwantedProperties.push('password');

    if (envelope && envelope.constructor === Array) {
      envelope.forEach(item: => {
        Helpers.cleanSOAP(item);
      });
    }

    else if (typeof envelope === 'object') {
      Object.getOwnPropertyNames(envelope)
        .forEach(key => {

          if (unwantedProperties.indexOf(key) !== -1) {
            delete envelope[key];
          }

          else if (envelope[key] === null) {
            delete envelope[key];
          }

          else if (envelope.hasOwnProperty(key) && typeof envelope[key] === 'object' && envelope[key] !== null && envelope[key].hasOwnProperty('$value')) {
            envelope[key] = envelope[key]['$value'];
          }

          else {
            Helpers.cleanSOAP(envelope[key]);
          }
        });
    }
  }
1 Answers

The forEach function doesn't exist on an object in typescript as you can't iterate an object directly. You need to determine if the parameter is either an array or object an then iterate accordingly. For example:

function cleanSOAP(envelope: [] | {}, removePassword: boolean = false){
   if(Array.isArray(envelope)){
       envelope.forEach(it => doSomething(it))
   } else {
       Object.keys(envelope).forEach(key => doSomething(evelope[key]))
   }
}
Related