简体   繁体   English

使用 Object.keys 从映射对象输出键/值时出现打字稿错误

[英]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.尝试映射错误对象并显示键值和键作为锚点 href 时,我在 React 应用程序中收到以下 Typescript 错误。

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 组件的 Props:

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

What I am attempting to get in the resulting HTML is as follows:我试图在结果 HTML 中得到的内容如下:

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

Thanks so much.非常感谢。

ErrorProps.errors is a type , not a namespace . ErrorProps.errors是一种类型,而不是命名空间 Consider changing the way how you retrieve the nested type.考虑更改检索嵌套类型的方式。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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