skip to Main Content

I need to avoid the using of ‘any’ as type definition while pushing the element into array. I tried to provide the type but I am getting an error. Here is the sample code

interface answerProps {
    state: string;
    answer: string;
  }

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

As per the above code , I wanted to avoid of using any while mapping the array element.

2

Answers


  1. Just use the answerProps interface while mapping the array.

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

    note 1
    there are 2 ways of casting a typed array. For my example, I mainly used the 2nd casting method

    • const arr1: Array<string>
    • const arr2: string[]

    note 2
    in your given sample, array.map is not the correct method to use, try using array.forEach instead

    note 3
    array.map when used correctly, allows typescript to automatically identify the resulted type, and is great to avoid manually casting type to variables

    note 4
    (this is purely preferences) rather then guarding against empty array, try to refactor your code so that it will accepts empty array as valid. In the example I have given above, an empty answers will gets mapped to an empty results

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search