Home > OS >  What is the function return type that can handle type null?
What is the function return type that can handle type null?

Time:03-23

I'm trying to implement conditional rendering in typescript and currently when null is used as alternative I get following error message

"Type 'Element | null' is not assignable to type 'Element'. Type 'null' is not assignable to type 'ReactElement<any, any>'"

So if I delete JSX.Element then typescript complains missing type on return function. Other alternative is to replace null with (<></>). This works but I read somewhere this takes extra space in dom so null is better solution. So is there function return type that can handle null or any alternative approach to this?

export const ContextPanel = ({
  children,
}: React.PropsWithChildren<LayoutContextInterface>): JSX.Element => {
  const context = React.useContext(LayoutContext);
  return context.contextPanelOpen ? (
    <div className={styles.contextPanelWidth}>{children}</div>
  ) : null;
};

CodePudding user response:

I'd suggest using the FunctionComponent type instead (check it out for details on what the proper return type is if you want to manually type it yourself.

export const ContextPanel: React.FunctionComponent = ({
  children
}) => {
  const context = React.useContext(LayoutContext);
  return context.contextPanelOpen ? (
    <div className={styles.contextPanelWidth}>{children}</div>
  ) : null;
};

For reference, here is the definitition of the FunctionComponent interface at the time of writing this answer. See the link for an up-to-date version.

 interface FunctionComponent<P = {}> {
        (props: PropsWithChildren<P>, context?: any): ReactElement<any, any> | null;
        propTypes?: WeakValidationMap<P> | undefined;
        contextTypes?: ValidationMap<any> | undefined;
        defaultProps?: Partial<P> | undefined;
        displayName?: string | undefined;
    }

Note the return type here is ReactElement<any, any> | null. I suspect your original answer would've worked if you simply typed your return properly with JSX.Element | null, but overall this typing is probably more accurate.

  • Related