组件 which prop 必须是特定 React 元素的数组

Dav*_*mes 13 typescript reactjs

我正在尝试编写一个组件,它接受另一个组件的实例数组作为道具。该组件 is MyComponent,它接受一组 的实例Title作为其参数之一。但是,我无法让 TypeScript 进行类型检查:

import * as React from "react";


type TitleProps = {
    name: string;
};

function Title(props: TitleProps) {
    return null;
}

type MyComponentProps = {
    titles: Array<React.ReactElement<TitleProps>>;
}

function MyComponent({ titles }: MyComponentProps) {
    return <div>{titles}</div>;
}

function OtherComponent(props: {}) { return null }

const shouldError = <MyComponent titles={[ <div/>, <OtherComponent/> ]} />;
const shouldNotError = <MyComponent titles={[ <Title name="hi"/>, <Title name="hi2"/>, ]} />;
Run Code Online (Sandbox Code Playgroud)

如您所见,我可以将任何我想要的东西传递给titlesprop,而不仅仅是<Title/>.

打字稿游乐场网址

Cod*_*ing 4

TypeScript 并不是灵丹妙药。在许多情况下,保证 100% 的类型安全需要在代码中引入额外的复杂性,或者根本不可能。你就遇到过这样一种情况。

一个关于输入 JSX 元素主题的开放 GitHub 问题。最好的选择是等待 TypeScript 为此引入特定的机制。

否则(来自马特·麦卡琴的回答):

所有 JSX 元素都被硬编码为 JSX.Element 类型,因此无法接受某些 JSX 元素而不接受其他元素。如果您想要进行这种检查,则必须放弃 JSX 语法,定义自己的元素工厂函数,该函数包装 React.createElement 但为不同的组件类型返回不同的元素类型,并手动编写对该工厂函数的调用。

因此,目前还没有办法确保任何 JSX 元素的类型安全