在 React 中,通常使用 null
表示 Prop 是可选的:
function Foo({ count = null }) {}
此 TS 类型为:
function Foo({ count = null }: { count: number | null }): ReactElement {}
我认为| null
看起来不干净,我正在寻找一种更好的方法来做到这一点。一种选择是:
function Foo({ count }: { count?: number }): ReactElement {}
但是,这打破了指定默认 Prop 的 React 最佳实践。我必须禁用 Eslint react/require-default-props
规则。对于开发人员来说,哪些 Prop 是可选的仍然很明显。主要问题是我必须处理 undefined
更频繁,例如<Foo count={someCondition ? 123 : undefined} />
.
有没有更好的方法?最好是一种让我将默认 Prop 保留为 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 {}
关于javascript - 有没有办法用 Typescript 使可选的 React props 类型更清晰?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63430398/