ThomasReggi
ThomasReggi

Reputation: 59505

How do I set return type to React.StatelessComponent?

This is working:

import * as React from 'react';

export default (props: any): JSX.Element => {
  return (
    <h1>{props.children}</h1>
  )
}

And this is throwing an error:

import * as React from 'react';

export default (props: any): React.StatelessComponent => {
  return (
    <h1>{props.children}</h1>
  )
}

How do I set the return type to React.StatelessComponent?

Upvotes: 1

Views: 159

Answers (3)

Nurbol Alpysbayev
Nurbol Alpysbayev

Reputation: 21961

Do not use default export, its an antipattern.

import * as React from 'react';

export const MyComponent: React.StatelessComponent = (props) => <h1>{props.children}</h1>

Note that I also removed return keyword and curly braces, because its an arrow function and it does not do anything other than returning JSX

Upvotes: 1

Arman Charan
Arman Charan

Reputation: 5797

To declare and cast in the same statement - you're probably going to have to set the type of your component using as.

See below for a practical example.

// Types.
type Props = any

// Export.
export default (props => 
  <h1>{props.children}</h1>
) as React.StatelessComponent<Props>

Upvotes: 0

Mrchief
Mrchief

Reputation: 76258

Actually, you need to split the component and its export:

const MyComp: SFC<{}> = (props: any) => {
  return (
    <h1>{props.children}</h1>
  )
}

export default MyComp

Upvotes: 0

Related Questions