TypeScript:预期类型来自 属性 'children',它在 'IntrinsicAttributes & Prop' 上声明

TypeScript: Expected type comes from property 'children' which is declared on 'IntrinsicAttributes & Prop'

我正在开发一个组件,该组件包含一个子道具,该道具包含一个 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 是什么,我可以看到它正在用另一种类型 IntrinsicAttributes 扩展我的 Prop,但不确定为什么。当我删除 otherProp 时,错误似乎也消失了。解释会很有帮助。 非常感谢。

类型ImgHTTMLAttributes<HTMLImageElement>是描述一个简单对象的类型,它包含imgjsx元素可以接受的所有属性。 Pick<ImgHTMLAttributes<HTMLImageElement>, "src" | "alt"> 只是一个类型 { 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 组件时,其道具类型由 IntrinsicAttributes & PropsThathYouDefinedForYourComponent 类型描述,在您的情况下,IntrinsicAttributes & Props。这样,当你使用这个 jsx 组件时,你可以同时传递你的自定义 props 和内部库 props,并且类型检查仍然有效