【发布时间】:2021-01-03 09:40:39
【问题描述】:
我有一个组件除了children 之外没有任何道具,即:
function Foo({ children }: React.PropsWithChildren<>) {}
React.PropsWithChildren 需要一个参数。如果我做React.PropsWithChildren<{}>,Eslint 会产生Don't use `{}` as a type. `{}` actually means "any non-nullish value".。
我将它用于空对象类型:
type EmptyObj = { [k: string]: never };
但是,React.PropsWithChildren<EmptyObj> 导致:
Type '{ children: Element; }' is not assignable to type 'EmptyObj'.
Property 'children' is incompatible with index signature.
Type 'Element' is not assignable to type 'never'.
我应该将什么传递给React.PropsWithChildren?
编辑:
我知道我能做到:
function Foo({ children }: { children?: React.ReactNode }) {}
但是,我在整个代码库中都使用React.PropsWithChildren,所以我希望保持一致。
【问题讨论】:
-
你能重新创建类型错误吗?您配置了一些不常见的规则,即使 obj 为空,我也没有收到任何警告:codesandbox.io/s/hungry-benz-35y0l?file=/src/App.tsx:0-220
-
我忘了说我正在使用
typescript-eslint -
另外,您也可以禁用 eslint 规则。总是让我感到惊讶的是,人们有时会跳过去让 eslint 开心。 Eslint 应该让你的代码更好。如果您认为某条规则不适用,请不要使用该规则
-
这是一条有用的规则,令人沮丧的是打字稿
-
我会以牺牲清晰度为代价来争论一致性是没有意义的。就像,如果有一个更简单的方法(你引用它)为什么不直接使用它呢?相反,您会遇到 ESLint 警告,因为该类型没有意义,并且您使用更复杂的东西“解决它”(接受的答案)。如果你真的嫁给了
React.PropsWithChildren<{}>,为什么不直接用comment-pragma 让ESLint 警告静音呢?完全理解想要知道如何去做的愿望,但随后真正去做......不计算。
标签: javascript reactjs typescript