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
Just use the
answerProps
interface while mapping the array.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 usingarray.forEach
insteadnote 3
array.map
when used correctly, allows typescript to automatically identify the resulted type, and is great to avoid manually casting type to variablesnote 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