【问题标题】:TypeScript: Expected type comes from property 'children' which is declared on 'IntrinsicAttributes & Prop'TypeScript:预期类型来自在“IntrinsicAttributes & Prop”上声明的属性“children”
【发布时间】:2021-12-14 22:25:12
【问题描述】:

我正在开发一个组件,该组件接收一个 children 道具,该道具接收一个 img 元素 + 另一个道具。但是当我继续使用该组件并传递所有道具时,我收到以下错误:

Type 'Element' has no properties in common with type 'Pick<ImgHTMLAttributes<HTMLImageElement>, "src" | "alt">'.ts(2559)

App.tsx(5, 3): The expected type comes from property 'children' which is declared here on type 'IntrinsicAttributes & Props'

这是我的代码示例 (Link to CodeSandbox):

type Props = {
  children: Pick<ImgHTMLAttributes<HTMLImageElement>, "src" | "alt">
  otherProp?: any
}

const Image = ({children, otherProp}: Props) => {
  return (
    <picture>
      ...
      {children}
    </picture>
  )
}

老实说,我不明白IntrinsicAttributes 是什么,我可以看到它正在扩展我的Prop 与其他类型的IntrinsicAttributes,但不知道为什么。当我删除otherProp 时,错误似乎也消失了。一个解释会非常有帮助。 非常感谢。

【问题讨论】:

    标签: reactjs typescript typeerror


    【解决方案1】:

    ImgHTTMLAttributes&lt;HTMLImageElement&gt; 类型是一种描述简单对象的类型,它包含img jsx 元素可以接受的所有属性。 Pick&lt;ImgHTMLAttributes&lt;HTMLImageElement&gt;, "src" | "alt"&gt; 只是一个类型 { src: string; alt: string }。请注意,它没有描述实际的 img jsx 元素,它只是描述了它可能拥有的道具。

    在打字稿中没有办法说“这个组件只接受一个img jsx 元素,它只有道具altsrc”所以没有办法输入这个,至少不像你显示的那样沙盒。您可能应该做的是首先摆脱children,并将srcalt 直接传递给Image 组件

    interface Props {
      src: string
      alt: string
      otherProp?: any;
    }
    
    const Image = ({ src, alt, otherProp }: Props) => {
      return <picture><img src={src} alt={alt} /></picture>;
    };
    
    const el = <Image otherProp="" src="cool" alt="Image alt tag" />
    
    

    或者,如果您不想自己为 srcalt 编写类型定义,您可以像在示例中那样从 ImgHTTMLAttributes 中获取现有类型,但它应该如下所示:

    type Props = Pick<ImgHTMLAttributes<HTMLImageElement>, "src" | "alt"> & {
      otherProp?: any;
    }
    
    const Image = ({ src, alt, otherProp }: Props) => {
      return <picture><img src={src} alt={alt} /></picture>;
    };
    
    const el = <Image otherProp="" src="cool" alt="Image alt tag" />
    
    

    谈到IntrinsicAttributes,这是一种描述所有组件可以接收的道具的类型,即使您没有在道具定义中提供它们。它们通常由库内部使用,这就是它们被称为内在的原因。例如,如果您正在使用 react,则唯一的内在属性是 key:您可以将其附加到任何组件而无需在任何地方定义其类型,并且它在 react 内部使用。当您使用任何 jsx 组件时,其 prop 类型由 IntrinsicAttributes &amp; PropsThathYouDefinedForYourComponent 类型描述,在您的情况下为 IntrinsicAttributes &amp; Props。这样,当你使用这个 jsx 组件时,你可以同时传递你的自定义 props 和内部库 props,并且类型检查仍然有效

    【讨论】:

      猜你喜欢
      • 2022-07-05
      • 2020-09-03
      • 2022-08-18
      • 2021-07-12
      • 2021-08-20
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 2018-10-14
      相关资源
      最近更新 更多