I'm trying to improve my code by avoiding repetitive lines like this:
handleUserChange?.({ target: { name: 'first_name', value: rentalOrder?.address?.first_name } })
handleUserChange?.({ target: { name: 'last_name', value: rentalOrder?.address?.last_name } })
handleUserChange?.({ target: { name: 'address_line_one', value: rentalOrder?.address?.address_line_one } })
Instead, I came up with a more efficient solution:
const fieldsFromDeliveryAddress = ['first_name', 'last_name', 'address_line_one', 'post_code', 'city', 'phone']
fieldsFromDeliveryAddress.forEach(fieldName => handleUserChange?.({ target: { name: fieldName, value: rentalOrder?.address?.[fieldName] } }))
However, this approach is generating a TypeScript error (specifically on line 2 where
rentalOrder?.address?.[fieldName]
is highlighted in red):
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ first_name: string; last_name: string; email?: string | undefined; address_line_one: string; address_line_two?: string | undefined; country: string; city: string; post_code: string; phone: string; }'.
No index signature with a parameter of type 'string' was found on type '{ first_name: string; last_name: string; email?: string | undefined; address_line_one: string; address_line_two?: string | undefined; country: string; city: string; post_code: string; phone: string; }'
What would be the best way to resolve this issue?
Update
Definitions of functions involved:
const handleUserChange = ({ target }: HTMLSimpleElementEvent): void
interface HTMLSimpleElementEvent {
target: {
name: string
type?: string
value?: any
checked?: boolean
}
}