2
votes

I am trying to code a React Stateless Function component in TypeScript. Please see the code below:

import * as React from 'react';
import {observer} from 'mobx-react';

export interface LinkProps {
    view: any;
    className: any;
    params?: any;
    queryParams?: any;
    store?: any;
    refresh: boolean;
    style?: any;
    children: any;
    title?: any;
    router: any;
}

const Link: React.SFC<LinkProps> = (   // <----- Error on this line
    {
        view,
        className,
        params = {},
        queryParams = {},
        store = {},
        refresh = false,
        style = {},
        children,
        title = children,
        router = store.router
    }) => {
    ...
}

export default observer(Link);

However the compiler is giving me an error on const Link:

src/components/Link.tsx(17,7): error TS2322: Type '({ view, className, params, queryParams, store, refresh, style, children, title, router }: LinkPr...' is not assignable to type 'StatelessComponent'. Type 'void | Element' is not assignable to type 'ReactElement'. Type 'void' is not assignable to type 'ReactElement'.

What am I doing wrong?

Here are the version dependencies in my pckage.json file:

"@types/react": "^16.0.29",
"@types/react-dom": "^16.0.3",
"del-cli": "^1.1.0",
"mobx": "^3.4.1",
"mobx-react": "^4.3.5",
"react": "^16.2.0",
"typescript": "^2.6.2"

Thanks in advance!

2
try React.SFC<LinkProps, {}> ... the msg say : is not assignable to type 'StatelessComponent'. If the error goes away, then we know you can only work with this function with a state component - theforce
Unfortunately that doesn't work. Here's the error: src/components/Link.tsx(17,13): error TS2707: Generic type 'SFC' requires between 0 and 1 type arguments. - Naresh
ah, thx for your feedback try: const Link: React.SFC<LinkProps> = (props) => { return...your impl} we forgot the argument - theforce
Hi Glen, it's not that because that would just replace my destructuring with a single props variable. In fact, the answer is close @AluanHaddad's comment. There were multiple returns in the body of the code and one of them did not return an element - it said return console.log(....), thus returning a void (porting someone else's code!). So Aluan, if you put down your comment as an answer, I will mark it as correct. Thank you both for helping. - Naresh
Yep, I will be doing extensive refactoring once I get the code running. Currently porting this from a ES2015 codebase. - Naresh

2 Answers

0
votes

Just remove children in interface LinkProps. And I think you should read this

Have fun.

3
votes

This happens if you don't return a JSX element. Also if you return a function that returns a JSX element the issue also will happen. To avoid from this issue you can just return <React.Fragment> as an empty element and put your function inside it:

<React.Fragment>
    {yourFunction()}
</React.Fragment>