如何强制孩子拥有某种属性

问题描述 投票:0回答:1

正如标题所说,我有一个像这样的react FC:

const Test = (props: { 
    children: React.ReactElement<{ slot: "content" }> 
}) => {
    return <></>
}

现在,传递一个没有slot属性的child,没有任何ts错误

const test = (
    <Test>
        <span>some content</span>
    </Test>
)

我怎么会收到 ts 错误,指出 span 没有 slot 属性

reactjs typescript
1个回答
0
投票

试试这个

type ChildProps = {
  slot: string;
};

const Test: React.FC<{ children: React.ReactElement<ChildProps> }> = (props) => {
  return <>{props.children}</>;
};
© www.soinside.com 2019 - 2024. All rights reserved.