【发布时间】:2021-03-07 02:17:37
【问题描述】:
我正在用打字稿编写反应应用程序。 为了提供类型化的道具,我使用下面的代码。
type ScheduleBoxContentProps = {
desc: ReactNode,
lottie: LottieProps,
} & Partial<{className: string}>;
如您所见,我希望 className 属性是可选的,但不想为它定义 defaultProps。此外,还应提供desc 和lottie 道具。
有没有更好的方式来定义optional without default?
编辑
我很抱歉缺少上下文。
如果我将React.FC 与我的自定义道具类型一起使用,那么没有问题。因为React.FC 在里面使用了Partial。
type MyProps = {
className?: string;
}
// no erros and warnings
const Component: React.FC<MyProps> = (props) => <div />;
但我不希望我的组件接受 children 道具。我希望我的组件在 children 道具到来时发出警报。因此,我正在使用带有以下代码的功能组件。
// error: default value for className is not provided.
const Component = ({className}: MyProps) => <div className={className} />;
它告诉我className 的默认值已定义。我应该明确定义它。使用下面的代码。
Component.defaultProps = {className: ''};
IMO,似乎有点不必要的代码,所以我决定在可选道具上使用Partial。
type MyProps = Partial<{className: string}>;
有没有更好的方法来实现这一点?或者,使用defaultProps 是最佳做法?
【问题讨论】:
标签: reactjs typescript