简体   繁体   中英

Typescript error when outputting key/value from mapped Object with Object.keys

I am getting the following Typescript error in a React application when attempting to map over an object of errors and display the key value, and the key as the anchor href.

Element implicitly has an 'any' type because expression of type '"errors"' can't be used to index type '{ paid?: string | undefined; }'.
  Property 'errors' does not exist on type '{ paid?: string | undefined; }'.ts(7053)

Below is the Component

interface ErrorProps {
  errors: {
    paid?: string
  }
}

function Error(props: ErrorProps) {
  return (
    <ul>
      {props.errors && Object.keys(props.errors).map(key => {
        return (
          <li key={key}>
            <a href={`#${key}`}>
              {props.errors[key as keyof ErrorProps.errors]} // The error is on this line
            </a>
          </li> 
        )
      })}
    </ul>
  )
}

The following is the Props passed to the Errors Component:

errors: {paid: "Paid must be a number"}

What I am attempting to get in the resulting HTML is as follows:

<a href="#paid">Paid must be a number</a>

Thanks so much.

ErrorProps.errors is a type , not a namespace . Consider changing the way how you retrieve the nested type.

{props.errors[key as keyof ErrorProps['errors']]} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM