Fix ESLint warnings in next.js's _document.tsx thrown by Document<any> and ctx.renderPage = () when using TypeScript

Viewed 3952

maxbause was kind to create a nice boilerplate project for Next.js that includes GraphQL and styled components in TypeScript.

https://github.com/maxbause/next-graphql-styled-components-ts-boilerplate/blob/master/pages/_document.tsx

Nonetheless, when I added ESLint to the project I got several warnings and errors because the cause was basically plain JavaScript.

I fixed most of it but I am stuck with two warnings in the _document.tsx file.

First of all, I am getting the following warning on the any part of Document< any>: "Unexpected any. Specify a different type." If I remove any and use nothing, unknown or never then I get errors with the this.props.styleTags.

The second issue is with the Missing return type on function warning thrown by the missing return type in ctx.renderPage = () => right after the try where I don't know what I should add.

I am a bit of a noob in TypeScript so please don't be too harsh on me if there is an obvious solution to this. I search quite a bit but couldn't figure it out.

I know I can ignore or even disable these errors but if I am to disable the errors I would appreciate if you could explain why it makes sense to do so.

I hope this question is useful to everyone interested in using Next.js with TypeScript.

_document.tsx (where the warnings are thrown)

import React from 'react';
import Document, { Head, Main, NextScript, DocumentContext, DocumentInitialProps } from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document<any> {
    static async getInitialProps(ctx: DocumentContext): Promise<DocumentInitialProps> {
        const sheet = new ServerStyleSheet();
        const originalRenderPage = ctx.renderPage;

        try {
            // wraps the collectStyles provider around our <App />.
            ctx.renderPage = () =>
                originalRenderPage({
                    enhanceApp: App => (props): React.ReactElement => sheet.collectStyles(<App {...props} />),
                });

            // extract the initial props that may be present.
            const initialProps = await Document.getInitialProps(ctx);

            // returning the original props together with our styled components.
            return {
                ...initialProps,
                styles: (
                    <>
                        {initialProps.styles}
                        {sheet.getStyleElement()}
                    </>
                ),
            };
        } finally {
            sheet.seal();
        }
    }

    render(): JSX.Element {
        return (
            <html>
                <Head>{this.props.styleTags /*rendering the actually stylesheet*/}</Head>
                <body>
                    <Main />
                    <NextScript />
                </body>
            </html>
        );
    }
}

.eslintrc.js

var OFF = 0, WARN = 1, ERROR = 2;

module.exports = {
    parser: '@typescript-eslint/parser', // Specifies the ESLint parser
    extends: [
        'plugin:react/recommended', // Uses the recommended rules from @eslint-plugin-react
        'plugin:@typescript-eslint/recommended', // Uses the recommended rules from the @typescript-eslint/eslint-plugin
        'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier
        'plugin:prettier/recommended', // Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
    ],
    parserOptions: {
        ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features
        sourceType: 'module', // Allows for the use of imports
        ecmaFeatures: {
            jsx: true, // Allows for the parsing of JSX
        },
    },
    rules: {
        '@typescript-eslint/interface-name-prefix': [ERROR, {'prefixWithI': 'always'}]
        // Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs
        // e.g. "@typescript-eslint/explicit-function-return-type": "off",
    },
    settings: {
        react: {
            version: 'detect', // Tells eslint-plugin-react to automatically detect the version of React to use
        },
    },
};

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve"
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ]
}

package.json

{
    "name": "killer-frontend",
    "version": "1.0.0",
    "main": "index.js",
    "license": "MIT",
    "dependencies": {
        "@apollo/react-hooks": "^3.1.3",
        "apollo-boost": "^0.4.7",
        "graphql": "^14.5.8",
        "next": "^9.1.6",
        "next-with-apollo": "^4.3.0",
        "node-fetch": "^2.6.0",
        "react": "^16.12.0",
        "react-dom": "^16.12.0",
        "styled-components": "^5.0.1"
    },
    "scripts": {
        "dev": "next",
        "build": "next build",
        "start": "next start",
        "lint": "tsc --noEmit && eslint '*/**/*.{js,ts,tsx}' --quiet --fix"
    },
    "devDependencies": {
        "@types/node": "^13.1.1",
        "@types/react": "^16.9.17",
        "@types/styled-components": "^5.0.1",
        "@typescript-eslint/eslint-plugin": "^2.23.0",
        "@typescript-eslint/parser": "^2.23.0",
        "babel-plugin-styled-components": "^1.10.7",
        "eslint": "^6.8.0",
        "eslint-config-prettier": "^6.10.0",
        "eslint-plugin-prettier": "^3.1.2",
        "eslint-plugin-react": "^7.19.0",
        "prettier": "^1.19.1",
        "typescript": "^3.7.4"
    }
}
3 Answers

Hope it's still useful to you.

EDIT: I should note that I am not sure if this is the correct typing. However this does silence the TypeScript linter without giving it an implicit any type.

ctx.renderPage = (): RenderPageResult | Promise<RenderPageResult> =>
    originalRenderPage({
            enhanceApp: (App) => (props): ReactElement =>
                sheet.collectStyles(<App {...props} />),
        });
    ```

For the first issue for the Document type and for the this.props.styleTags warning, I found this answer by meenie where you need to create an interface as follows:

interface IProps {
    styleTags: unknown;
}

export default class MyDocument extends Document<IProps> {
    ...
}

Unlike the answer on the link above, you need to declare the interface with an I in front of its name as a good naming practice in TypeScript.

Thanks to julicolo's answer I was able to find this question where I went with Evgeny's answer since it seems more elegant and avoids the import.

ctx.renderPage = (): ReturnType<typeof ctx.renderPage>
static getInitialProps({ renderPage }: DocumentContext): Promise<RenderPageResult> {
   return Promise.resolve<RenderPageResult>(renderPage())
}

Worked for me

UPD, with styled-components

static async getInitialProps(ctx: DocumentContext): Promise<RenderPageResult> {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;
    const initialProps = await Document.getInitialProps(ctx);

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
        });

      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      } as RenderPageResult;
    } catch {
      return initialProps;
    } finally {
      sheet.seal();
    }
  }
Related