Skip to content

JSX does not accept functional components that can return null types #14570

Closed
@apexskier

Description

@apexskier

TypeScript Version: 2.2.1

Code

import * as React from "react";

interface TestStatelessProps {
    output: boolean;
}

function TestStateless(props: TestStatelessProps): JSX.Element | null {
    if (props.output) {
        return <div>Hello World</div>;
    }
    return null;
}

const test = (
    <div>
        1: {null}
        2: <TestStateless output />
        3: <TestStateless output={false} />
    </div>
);
console.log(test);

Expected behavior:
Compiles. test has type JSX.Element. If test were rendered it would show

<div>1:2:<div>Hello World</div>3:</div>

Null wouldn't render anything, the first TestStateless would render it's content, the second wouldn't render anything.

Actual behavior:
If I try to use <TestStateless />, I get the following errors.

[ts] JSX element type 'Element | null' is not a constructor function for JSX elements.
  Type 'null' is not assignable to type 'ElementClass'.
[ts] JSX element class does not support attributes because it does not have a 'props' property

The {null} part of the JSX works correctly.
The same issue happens if the functional component returns undefined

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions