2

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
  • Can you show the rest of the code where you verify its type and call forEach? Commented Jun 8, 2020 at 23:35

1 Answer 1

1

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]))
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you ! My verification was not "strong enough" for TypeScript :) with isArray error disappeared.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.