【问题标题】:typescript: Better way to type optional without default value?typescript:在没有默认值的情况下键入可选的更好方法?
【发布时间】:2021-03-07 02:17:37
【问题描述】:

我正在用打字稿编写反应应用程序。 为了提供类型化的道具,我使用下面的代码。

type ScheduleBoxContentProps = {
  desc: ReactNode,
  lottie: LottieProps,
} & Partial<{className: string}>;

如您所见,我希望 className 属性是可选的,但不想为它定义 defaultProps。此外,还应提供desclottie 道具。

有没有更好的方式来定义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


    【解决方案1】:

    您可以在属性名称后添加?

    type ScheduleBoxContentProps = {
      desc: ReactNode,
      lottie: LottieProps,
      
      // This ? is literally what Partial does
      className?: string,
    };
    

    至于您编辑的示例,我认为最简单的是在解构语法中设置默认值:

    const Component = ({className = ''}: MyProps) => <div className={className} />;
    

    【讨论】:

    • 抱歉缺少上下文。我添加了一些关于我的情况的更多信息。
    • 我用可能的解决方案编辑了我的回复
    • 我想得太复杂了。你用基本的方法给我指出了正确的解决方案:)非常感谢!如果发生这种情况,我会将您的解决方案用于简单的道具,将Partial 用于其他复杂的道具。
    【解决方案2】:

    怎么样

    className?: string;
    

    【讨论】:

    • 抱歉缺少上下文。我添加了一些关于我的情况的更多信息。
    猜你喜欢
    • 2011-11-20
    • 1970-01-01
    • 2019-10-19
    • 2018-09-17
    • 2016-05-27
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    • 2012-11-28
    相关资源
    最近更新 更多