最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Binding element 'children' implicitly has an 'any' type.ts(7031) in Next.js - Stack

programmeradmin1浏览0评论

While developing my personal portfolio using Next.js, I ran into an error where the prop "children" was not working. I am using tsx.

Layout.tsx

import styles from "./layout.module.css";

export default function Layout({ children, ...props }) {
  return (
    <>
      <main className={styles.main} {...props}>{children}</main>
    </>
  );
}

I tried using other props, defining the props, like I was from tutorials online, but none of them worked. ;(

While developing my personal portfolio using Next.js, I ran into an error where the prop "children" was not working. I am using tsx.

Layout.tsx

import styles from "./layout.module.css";

export default function Layout({ children, ...props }) {
  return (
    <>
      <main className={styles.main} {...props}>{children}</main>
    </>
  );
}

I tried using other props, defining the props, like I was from tutorials online, but none of them worked. ;(

Share Improve this question asked Dec 3, 2022 at 19:56 David GuriDavid Guri 1631 silver badge10 bronze badges 1
  • Those fragments (<>) are not necessary. You can learn more here: reactjs/docs/fragments.html – ddblair Commented Dec 3, 2022 at 20:10
Add a ment  | 

2 Answers 2

Reset to default 8

Your filetype is .tsx, which is a TypeScript filetype. You have to either define the types of the props, or change the file's name to Layout.js to convert it to vanilla JavaScript.

If you want to use TypeScript:

import { ReactNode } from "react";
import styles from "./layout.module.css";

const type LayoutProps = {
  children: ReactNode;
  // Your other props here.
}

export default function Layout({ children, ...props }: LayoutProps) {
  return (
    <>
      <main className={styles.main} {...props}>{children}</main>
    </>
  );
}

The issue is that when TypeScript doesn't know the type of something, it will assume the type is any and plain. You could explicitly set the type as any to solve this problem, as well, but this is considered bad practice:

export default function Layout({ children, ...props }: any) {
  return (
    <>
      <main className={styles.main} {...props}>{children}</main>
    </>
  );
}

One way to define a layout.tsx file in typescript with Next.js 14+ we can import the LayoutProps:

import { LayoutProps } from "@/.next/types/app/page";
import styles from "./layout.module.css";

export default function Layout({ children, ...props }: LayoutProps) {
    return (
    <>
        <main className={styles.main} {...props}>{children}</main>
    </>

); }

发布评论

评论列表(0)

  1. 暂无评论