javascript - 有没有办法使用 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 {}
解决方案
我不知道这听起来是否会是一个更干净的解决方案,并且您可以像下面这样明确定义参数类型可能会感觉有点麻烦:
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 {}
推荐阅读
- c# - OnSave EF Core 的 SQL 错误
- mysql - 不支持 LOCK=NONE。原因:添加列列...虚拟,添加索引(列)。尝试 LOCK=SHARED
- angular - 从 Angular 11 升级到 12 会导致错误:此源的内容和地图不可用(仅支持 size())
- python - 如何在 TFX 的 Transform 组件中编写聚合函数?
- c++ - 用户输入不打印,有人知道为什么吗?
- design-patterns - 如何设计一个回货通知系统?
- python - 按下按钮时从 Flask 执行 shell 脚本
- python - 如何使用与列的唯一值匹配的列快速创建新数据框
- python - 我想用 Python、Pandas、Jupyter 中的另一个主表覆盖一个小表
- postgresql - 对 PostgreSQL 性能的理解