search

Home  >  Q&A  >  body text

How to provide a type definition when pushing elements into an array using TypeScript?

<p>I need to avoid using 'any' as a type definition when pushing elements into an array. I tried providing the type but I got an error. Here is sample code: </p> <pre class="brush:php;toolbar:false;">interface answerProps { state: string; answer: string; } const results: Array<string> = []; !isEmpty(answers) && answers.map((item: any) => results.push(`${item.state} : ${item.answer}`));</pre> <p>Based on the above code, I want to avoid using a while loop to map array elements. </p>
P粉745412116P粉745412116490 days ago469

reply all(1)I'll reply

  • P粉151466081

    P粉1514660812023-07-25 20:42:31

    When mapping arrays, just use the answerProps interface.

    interface answerProps {
      state: string;
      answer: string;
    }
    
    const results: Array<string> = [];
    !isEmpty(answers) &&
      answers.map((item: answerProps) => results.push(`${item.state} : ${item.answer}`));

    reply
    0
  • Cancelreply