【问题标题】:Is there a way to make optional React props types cleaner with Typescript?有没有办法使用 Typescript 使可选的 React 道具类型更清洁?
【发布时间】:2020-08-15 20:10:50
【问题描述】:

在 React 中,通常使用 null 来表示 prop 是可选的:

function Foo({ count = null }) {}

为此的 TS 类型是:

function Foo({ count = null }: { count: number | null }): ReactElement {}

我认为| null 看起来不干净,我正在寻找更好的方法来做到这一点。一种选择是:

function Foo({ count }: { count?: number }): ReactElement {}

但是,这打破了指定默认道具的 React 最佳实践。我必须禁用 Eslint react/require-default-props 规则。对于开发人员来说,哪些道具是可选的仍然很明显。主要问题是我必须更频繁地处理undefined,例如<Foo count={someCondition ? 123 : undefined} />.

有没有更好的方法?最好是让我将默认道具保留为null,同时保持 TS 类型干净?

编辑: 另一种选择是 nullables:

type N<T> = T | null;

function Foo({ count = null }: { count: N<number> }): ReactElement {}

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案1】:

    我不知道这听起来是否是一个更干净的解决方案,而且您可以像下面这样显式定义您的参数类型可能会觉得有点麻烦:

    class FooArg {
      constructor(public count: number | null = null) { } // you define your parameter logic here
    // define what is required etc.
    }
    
    // and use it like this
    function Foo(arg: FooArg): ReactElement {}
    
    // or all optional 
    function Boo(arg?: FooArg): ReactElement {}
    

    Playground Link

    【讨论】:

      猜你喜欢
      • 2017-11-28
      • 1970-01-01
      • 2022-11-20
      • 1970-01-01
      • 2021-06-19
      • 1970-01-01
      • 2019-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多