React.PropsWithChildren除了“children”之外没有其他道具?
我有一个除了 之外没有其他道具的组件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整个代码库中都在使用,所以我更愿意保持一致。
回答
解决办法是:
function Foo({ children }: React.PropsWithChildren<Record<never, any>>) {}
如果 eslint 警告您any使用类型Record<never, never>。
THE END
二维码