TypeScript:是否可以使用interae重写此帮助程序类型



我在阅读这篇博客文章时遇到了这种助手类型https://fettblog.eu/typescript-react-component-patterns/

type WithChildren<T = {}> = 
T & { children?: React.ReactNode };
type CardProps = WithChildren<{
title: string;
}>;

我们可以通过进行以下来使用这种类型


function Card({ title, children }: CardProps) {
return <>
<h1>{ title }</h1>
{children}
</>
}

我的问题是,是否可以使用interface重写此类型的helper?

是的,您可以简单地将类型组合成一个接口,如下所示:

interface CardProps {
title: string;
children?: React.ReactNode;
}

在自己的界面中添加children似乎不是最好的主意,我发现使用React.FC<Props>泛型更方便。你可以把你自己的界面传给它,孩子们也会自动添加

以下是如何将React.FC类型与箭头函数一起使用的示例:https://medium.com/@ethan_ikt/react-无状态-功能组件-带类型脚本-ce5043466011

最新更新