Typescript: StatelessFunctionalComponenet that probably returns null cannot be instanciated in JSX

Created on 31 Oct 2016  路  8Comments  路  Source: microsoft/TypeScript

TypeScript Version: 2.1.0-dev.20161019

Code

import * as React from 'react';
import { render } from 'react-dom';

interface FooProps extends React.Props<null> {
  prop1?: boolean;
}

const Foo = ({ prop1 }: FooProps) => {
  if (prop1) {
    return null;
  }
  return (
    <div>Hello!</div>
  );
}

render(<Foo />, null);

Expected behavior:

This is a valid JSX code. It is true that the return value of the SFC can be null but there is no way to check for its value in the code!

Actual behavior:

Compiler complains with these errors:

error TS2605: JSX element type 'Element | null' is not a constructor function for JSX elements.
  Type 'null' is not assignable to type 'ElementClass'.
Bug Duplicate

Most helpful comment

This is annoying. I worked abound it by asserting that null is not null: 馃槺

const Foo = ({ prop1 }: FooProps) => {
  if (prop1) {
    return null!; // <= never is assignable to anything, so the return type will be Element
  }
  return (
    <div>Hello!</div>
  );
}

All 8 comments

This is annoying. I worked abound it by asserting that null is not null: 馃槺

const Foo = ({ prop1 }: FooProps) => {
  if (prop1) {
    return null!; // <= never is assignable to anything, so the return type will be Element
  }
  return (
    <div>Hello!</div>
  );
}

@alitaheri Good idea. I just decided to remove strictNullChecks. But I will go with your workaround to fix the problem.

@yuit we should allow null as a return type for JSX functions

@yuit as well as null constructor functions

Can someone explain what is happening in @alitaheri's workaround? I've never seen the null! syntax before and I can't find any documentation on it.

@tamlyn This is where you can find information on it.

This is the same as #11566

This is not fixed yet.
React definition from DefinitelyTyped still needs to be updated since the original PR was reverted due to regressions with TypeScript < 2.3

Was this page helpful?
0 / 5 - 0 ratings

Related issues

CyrusNajmabadi picture CyrusNajmabadi  路  3Comments

blendsdk picture blendsdk  路  3Comments

Antony-Jones picture Antony-Jones  路  3Comments

jbondc picture jbondc  路  3Comments

kyasbal-1994 picture kyasbal-1994  路  3Comments