[Recharts] Fix type errors in TypeScript 「error TS2739: Type ‘{}’ is missing the following properties from type」

The implementation was done using the React graph drawing library ‘Recharts‘.

When the Tooltip content was set up, when running ‘yarn typecheck’,

‘error TS2739: Type ‘{}’ is missing the following properties from type’.

error occurred.
The results of improving the error are described.

Also, the Nextjs version in this article is “13.5.4” and the Rcharts version is “2.10.3”.

目次

Cause of error.

The reason was that the CustomTooltip did not have a type defined, but we were not sure how to define it.

import React from "react";
import {
  LineChart,
  Tooltip,
  ResponsiveContainer,
  TooltipProps,
} from "recharts";

const CustomTooltip = ({
  active,
  payload,
  label,
}) => {
  if (active && payload && payload.length) {
    return (
      <ToolTip>
        <TooltipText>{`${label}`}</TooltipText>
      </ToolTip>
    );
  }

  return null;
};

export function Chart(props: Props) {
  return (
        <ResponsiveContainer width="100%" height="100%">
          <LineChart data={data} margin={chartMargin}>
            ...
            <Tooltip content={<CustomTooltip />} />
          </LineChart>
        </ResponsiveContainer>
  );
}

Fixed code

Conclusion, you can define it with the type TooltipProps provided by recharts.

import {
  TooltipProps,
} from "recharts";

import {
  ValueType,
  NameType,
} from "recharts/types/component/DefaultTooltipContent";

Check here for the full code.

import React from "react";
import {
  LineChart,
  Tooltip,
  ResponsiveContainer,
  TooltipProps,
} from "recharts";
import {
  ValueType,
  NameType,
} from "recharts/types/component/DefaultTooltipContent";

const CustomTooltip = ({
  active,
  payload,
  label,
}: TooltipProps<ValueType, NameType>) => {
  if (active && payload && payload.length) {
    return (
      <ToolTip>
        <TooltipText>{`${label}`}</TooltipText>
      </ToolTip>
    );
  }

  return null;
};

export function Chart(props: Props) {
  return (
        <ResponsiveContainer width="100%" height="100%">
          <LineChart data={data} margin={chartMargin}>
            ...
            <Tooltip content={<CustomTooltip />} />
          </LineChart>
        </ResponsiveContainer>
  );
}

Summary

When using libraries, type definitions can be confusing, but this is usually solved by looking at the contents of the library.

よかったらシェアしてね!
目次