Home > Blockchain >  How fix binding element 'xyz' implicitly has an 'any' type?
How fix binding element 'xyz' implicitly has an 'any' type?

Time:06-30

Vscode show me:

Binding element 'id' implicitly has an 'any' type.ts(7031)

The problem concerned line 30: const paths = posts.map(({ id }) => ({ params: { id: ${id} } }));

Bellow code:

import React from "react";
import axios from "axios";
import { GetStaticProps } from "next";

export default function SSGPage({ post }: SSRPageProps) {
  console.log(post);
  return <main>{post.title}</main>;
}

export const getStaticProps: GetStaticProps = async ({ params }) => {
  if (!params?.id) {
    return {
      props: {},
      notFound: true,
    };
  }

  const res = await fetch(
    `https://jsonplaceholder.typicode.com/posts/${params.id}`
  );
  const post = await res.json();
  return {
    props: { post },
  };
};

export async function getStaticPaths() {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts");
  const posts = await res.json();
  const paths = posts.map(({ id }) => ({ params: { id: `${id}` } }));
  return {
    paths,
    fallback: false,
  };
}

interface SSRPageProps {
  post: {
    userId: number;
    id: number;
    title: string;
    body: string;
  };
}

CodePudding user response:

interface IPost {
 id: string;
}
....
const paths = posts.map(({ id }: IPost) => ({ params: { id: `${id}` } }));

CodePudding user response:

Since there is not type explicitly defined for posts, there is no type defined for the individual items in posts. posts takes up the type any. And now you are trying to destructure properties from elements in the posts array. Obviously TS won't be aware of the type of property id. So id is also implicitly assigned any.

Looking at your usage you can do this:

 const paths = posts.map(({ id } : { id :string}) => ({ params: { id: `${id}` } }));

Now you inform TS, that id property is of string type

  • Related