SolvedDefinitelyTyped @types/react Make it possible to render a string from a functional component

With current typings it is not possible to create a stateless component which returns a string, number, boolean... (new in React 16)

import React from 'react'

const TestString = () => {
    return 'Test String Component'
}

const Component = () => (
    <div>
        <TestString/>
    </div>
)

Error I get:

JSX element type 'string' is not a constructor function for JSX elements.

The first problem is that currently in the typings a stateless component cannot return anything else besides an instance of a React.Element. This should be changed to (I think, I've based it upon the changes on the rendermethod, see https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts#L422)

interface StatelessComponent<P = {}> {
        (props: P & { children?: ReactNode }, context?: any): ReactElement<any> | Array<ReactElement<any>> | string | number | null;
        propTypes?: ValidationMap<P>;
        contextTypes?: ValidationMap<any>;
        defaultProps?: Partial<P>;
        displayName?: string;
}

Second problem is that behind the scenes the compiler will convert the jsx to `React.createElement('Test String Component', null)``

I get a compiler error that is saying that this is not a valid value. Seems that it has to be one of the values specified in following list: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts#L3465.

Any thoughts on how this can be fixed?

23 Answers

✔️Accepted Answer

A workaround is to return a fragment.

return <>0</>

Other Answers:

Any news on this issue?

This issue is making us write a-typical React code to work around limitations imposed by TypeScript. The only way to squash these errors in a TypeScript way is to introduce additional DOM elements and/or React.Fragments these add overhead (generate garbage) and they aren't needed.

This isn't always a problem by it crops up every now and is triggered when you return valid things from React components that aren't exactly JSX.Element, for example, an array.

I'd be happy with a sensible type annotation to help things along but I have to squash these with imperfect things like additional layers and/or any. Not good.

So, any news on fix?

This is essentially a duplicate of #18912. Once microsoft/TypeScript#21699 is resolved we should be able to use ReactNode as a valid return type for function components which includes string and boolean.

More Issues: