Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type '({ articles }: Props) => JSX.Element' is not assignable to type 'NextPage<{}, {}>'

I'm just getting into React.js and Next.js after having used Vue.js before. I'm getting a strange typescript error, but weirdly it actually compiles despite VS Code complaining at me as though it wouldn't compile.

I'm trying to pass an array of Article into my home component as a prop.

Here the relevant code:

interface Article {
  userId: number;
  id: number;
  title: string;
  body: string;
}

interface Props {
  articles: Article | Article[];
}

const Home: NextPage = ({ articles }: Props) => {
  return (
    <div>
      {/* some stuff */}
    </div>
  );
};

Home is underlined in red and when I hover over gives the error:

const Home: NextPage<{}, {}>
Type '({ articles }: Props) => JSX.Element' is not assignable to type 'NextPage<{}, {}>'.
  Type '({ articles }: Props) => JSX.Element' is not assignable to type 'FunctionComponent<{}> & { getInitialProps?(context: NextPageContext): {} | Promise<{}>; }'.
    Type '({ articles }: Props) => JSX.Element' is not assignable to type 'FunctionComponent<{}>'.
      Types of parameters '__0' and 'props' are incompatible.
        Property 'articles' is missing in type '{ children?: ReactNode; }' but required in type 'Props'.

Any help or insights as to what could be going on here would be greatly appreciated.

like image 281
Piturnah Avatar asked Dec 21 '25 20:12

Piturnah


2 Answers

Call it this way,

const Home: NextPage<Props> = ({ articles }) => {//your code}

you're using NextPage type, I used that instead too. It's actually better to use const Home: NextPage as that will type both the component's props and return type.

like image 123
Sai Krishnadas Avatar answered Dec 23 '25 12:12

Sai Krishnadas


you can write like this :

import React , {FC} from 'react';

interface Article {
  userId: number;
  id: number;
  title: string;
  body: string;
}

interface HomeProps {
  articles: Article[];
}

const Home : FC<HomeProps> = ({articles}) => {

console.log('articles: ', articles)

  return (
    <div>
      {/* some stuff */}
    </div>
  );
};

and in the container :


const myArticles = [
 {
   userId: 1,
   id: 1,
   title: 'my title',
   body: 'my body',
 }
]
...
return (
 <Home articles={myArticles}>
) 
like image 45
Mersad Mirgholami Avatar answered Dec 23 '25 10:12

Mersad Mirgholami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!