Encountering an Eslint issue: "Function missing return type" while adding a styled component to _document.tsx in Next.js

Setting up my NextJS project with styled components and Typescript has been my current focus.

After consulting the official NextJS documentation, I successfully configured the _document.tsx file, which appears like this:

import Document, { DocumentContext } from 'next/document';

import { ServerStyleSheet } from 'styled-components';

class MyDocument extends Document {
    static async getInitialProps(ctx: DocumentContext) {
        const sheet = new ServerStyleSheet();
        const originalRenderPage = ctx.renderPage;
        try {
            ctx.renderPage = () =>
                originalRenderPage({
                    enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
                });

            const initialProps = await Document.getInitialProps(ctx);
            return {
                ...initialProps,
                styles: (
                    <>
                        {initialProps.styles}
                        {sheet.getStyleElement()}
                    </>
                ),
            };
        } finally {
            sheet.seal();
        }
    }
}

export default MyDocument;

However, a warning from ESLint now appears saying, "Missing return type on function."

Instead of disabling this feature in ESLint, what is the correct approach to address this issue?

Thank you!

Answer №1

After gaining a better understanding of TypeScript, I was able to rectify the warning that was issued. As pointed out by @juliomalves, the TS compiler requires a return in the function, which can be resolved as follows:

class UpdatedDocument extends Document {
    static async getInitialProps(
        ctx: DocumentContext,
    ): Promise<{
        styles: JSX.Element;
        html: string;
        head?: JSX.Element[];
    }> {
    ...
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Merge topics together in RxJS like zip

Is it possible to create an observable that combines two subjects in a unique way, different from the zip function? The goal is to combine two subjects so that when both have emitted values, the latest of their values is emitted. Then, after both emit at ...

Observable subscription does not result in updating the value

One of the challenges I'm currently facing in my Angular application is the synchronization of data from a server. To keep track of when the last synchronization took place, I have implemented a function to retrieve this information: fetchLastSyncDate ...

What is the reason for NextJS causing a permanent redirect when using res.writeHead()?

Within my code, there is a specific section that checks for a certain condition to be true before redirecting. The relevant portion of the code is as follows: static async getInitialProps({ res }) { let accessToken = settings.get('access_toke ...

The TypeScriptLab.ts file is generating an error message at line 23, character 28, where it is expecting a comma

I am attempting to convert a ts file to a js file. My goal is to enter some numbers into a textarea, and then calculate the average of those numbers. However, I encountered an error: TypeScriptLab.ts(23,28): error TS1005: ',' expected. I have in ...

The issue with Elastic UI in NextJS is that it does not recognize the Window as defined

Struggling to integrate a button component from the Elastic UI library into my code. Every time I try to add the button, I encounter a window is not defined error. The API call and other functionalities work smoothly until I introduce the button component ...

Ways to eliminate the white background gap between pages on ionic

While developing an app using Ionic, I encountered a strange issue. Everything runs smoothly on a browser, but when testing the app on an Android 5 device, I noticed a white background appearing between pages. The app loads correctly with the custom splas ...

Instructions on incorporating domains into next.config.js for the "next/image" function with the help of a plugin

Here is the configuration I am currently using. // next.config.js const withImages = require("next-images"); module.exports = withImages({ webpack(config, options) { return config; }, }); I need to include this code in order to allow images from ...

Bring in personalized tag to TypeScript

I am working on a TypeScript file to generate an HTML page. Within this code, I want to import the module "model-viewer" and incorporate it into my project. import * as fs from "fs"; import prettier from "prettier"; import React from "react"; import ReactD ...

What is the method for defining functions that accept two different object types in Typescript?

After encountering the same issue multiple times, I've decided it's time to address it: How can functions that accept two different object types be defined in Typescript? I've referred to https://www.typescriptlang.org/docs/handbook/unions ...

How to Avoid 404 Errors When Using Next/Link in the App Directory

Here is a snippet of my NavBar() {/* Desktop Nav */} <div className="hidden md:flex items-center space-x-6"> <Link href={item1Href}> <div className="text-lg hover:text-gray-400">{i ...

Unlocking the power of variables in Next.js inline sass styles

Is there a way to utilize SASS variables in inline styles? export default function (): JSX.Element { return ( <MainLayout title={title} robots={false}> <nav> <a href="href">Title</a> ...

This TypeScript error occurs when the type of a CSS file lacks an index signature, resulting in an implicit 'any' type for the element

Currently in the process of transitioning a React app to utilize Typescript. Encountering an error message that reads: ERROR in [at-loader] ./src/components/Services/Services.tsx:34:29 TS7017: Element implicitly has an 'any' type because typ ...

Ways to recycle functional elements in Next.js 13 Server Components

Encountering a problem trying to separate the logic from the component due to this error message: Error: Event handlers cannot be passed to Client Component props. <textarea rows={18} placeholder=... onInput={function}> ...

Helping to maintain compatibility with previous URL structures using Next.js

Exploring a new Next.js project, I find myself in a situation where I must support legacy URLs without the ability to implement 301 redirects. The URLs I need to accommodate look like www.dan.com/foo/bar/slug As of now, my folder structure is arranged as ...

Why does "excess property checking" seem pleased when I utilize a key from set A or set B, even though "keyof (A|B)" is consistently "never"?

I am diving deeper into Typescript types and encountering some puzzling behavior: interface Person { name: string; } interface Lifespan { birth: number; death?: number; } let k: keyof (Person | Lifespan); //k is never let test1: Person | Life ...

Sending a POST request in Node.js and Express may result in the request body being empty or undefined

Here is a snippet of my Typescript code: import express = require('express'); const app: express.Application = express(); const port: number = 3000; app.listen(port, () => { console.log("The server is now running on port" + port); ...

Tips on overcoming errors while attempting to create a copy of an object using Spread, especially when the object's class contains abstract methods

In the code snippet below, there is an abstract class that requires extended classes to implement a specific method. However, when utilizing the "spread" syntax, an error occurs due to the missing implementation of the abstract method. abstract class Test ...

Antd CSS application is experiencing a delay

Upon refreshing the page on Next.js with Antd CSS, I am experiencing a delay in applying the styles. The content appears misaligned right after the reload. Is there a way to fix this issue? I suspect it may be related to SSR, but unfortunately, I have not ...

What are the best ways to maximize a web worker's ability to handle multiple tasks at once

I'm currently working on implementing a Web-Worker to handle its state while also managing multiple asynchronous requests. worker.ts file let a =0; //state of the worker let worker=self as unknown as Worker; worker.onmessage =(e)=>{ console ...

How can I retrieve data from the server in Next.js using higher order components (HOC)?

I recently developed a new application using Next.js version 9.3.1. In my previous app with SSR, I utilized the getInitialProps function in HOC components (not on the page itself) to fetch data from the server both in the HOC component and the page. You c ...