0

I want to avoid doing 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 } })

So instead I have:

const fieldsFromDeliveryAddress = ['first_name', 'last_name', 'address_line_one', 'post_code', 'city', 'phone']
fieldsFromDeliveryAddress.forEach(fieldName => handleUserChange?.({ target: { name: fieldName, value: rentalOrder?.address?.[fieldName] } }))

But it gives me the TypeScript error (on line 2, rentalOrder?.address?.[fieldName] is underlined 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; }'

How can I solve this?

Update

Function signatures:

const handleUserChange = ({ target }: HTMLSimpleElementEvent): void

interface HTMLSimpleElementEvent {
  target: {
    name: string
    type?: string
    value?: any
    checked?: boolean
  }
}
4
  • What's the type signature of handleUserChange? On what line do you get this error? Commented Apr 1, 2022 at 9:16
  • @ShamPooSham It's on line 2, see updated question Commented Apr 1, 2022 at 9:47
  • 1
    Try to do const fieldsFromDeliveryAddress = ['first_name', 'last_name', 'address_line_one', 'post_code', 'city', 'phone'] as const. Does that work? Commented Apr 1, 2022 at 10:19
  • @ShamPooSham Yes! If you add an Answer I will upvote Commented Apr 1, 2022 at 11:20

1 Answer 1

1

You need to add as const. Typescript will treat your array as a tuple and you'll have proper types for your forEach callback.

const fieldsFromDeliveryAddress = ['first_name', 'last_name', 'address_line_one', 'post_code', 'city', 'phone'] as const;
fieldsFromDeliveryAddress.forEach(fieldName => handleUserChange?.({ target: { name: fieldName, value: rentalOrder?.address?.[fieldName] } }))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.