首页 > 解决方案 > 有没有办法使用 Typescript 使可选的 React 道具类型更清洁?

问题描述

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

function Foo({ count = null }) {}

用于此的 TS 类型将是:

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

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

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

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

有没有更好的办法?最好是让我null在保持 TS 类型清洁的同时保留默认道具的方法?

编辑: 另一种选择是可为空的:

type N<T> = T | null;

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

标签: javascriptreactjstypescript

解决方案


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

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 {}

游乐场链接


推荐阅读