How to provide a type definition when pushing elements into an array using TypeScript?
P粉745412116
P粉745412116 2023-07-24 21:47:12
0
1
492
<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粉745412116
P粉745412116

reply all(1)
P粉151466081

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}`));
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template