Error in TypeScript: Typography type does not accept 'string' type as valid

As I attempt to implement the Typography component from material-ui using TypeScript, I encounter a perplexing error message

TypeScript is throwing an error: Type 'string' is not assignable to type 'ComponentClass<HTMLAttributes<HTMLElement>, any> | FunctionComponent<HTMLAttributes<HTMLElement>> | undefined'.  TS2322

     8 | }
     9 | export default ({ text, date }: Props) => (
  > 10 |   <Typography component="p" gutterBottom>
       |               ^
    11 |     {text && <span>{text}:&nbsp;</span>}
    12 |     <FormattedDate value={date} />
    13 |     &nbsp;

This is what my component currently looks like

import React from 'react';
import { FormattedDate, FormattedTime } from 'react-intl';
import Typography from '@material-ui/core/Typography';

interface Props {
  date: Date;
  text?: string;
}
export default ({ text, date }: Props) => (
  <Typography component="p" gutterBottom>
    {text && <span>{text}:&nbsp;</span>}
    <FormattedDate value={date} />
    &nbsp;
    <FormattedTime value={date} />
  </Typography>
);

I am puzzled by why "p" is being rejected as a valid value for the component prop. Similar issues arise when trying "h1" and "h2", despite the fact that the official demo uses strings in this way.

Is there something crucial that eludes me? I hesitate to simply bypass the problem with // @ts-ignore, and instead want to resolve it.

Answer №1

Back in 2021, I encountered an issue where I mistakenly spread the HTMLAttributes of an input instead of spreading InputBaseProps while working with a material UI component.

Although my case involved an input, this mistake can happen with any component. It is essential to provide the correct properties and set the appropriate prop types when using or extending material UI components.

Here's an example that caused an error:

import { HTMLAttributes } from 'react';

import InputBase from '@material-ui/core/InputBase';

import inputStyle from 'Input.module.scss';

export interface InputProps extends HTMLAttributes<HTMLInputElement> {
  
}

export function Input(props: InputProps) {
  const { ...rest } = props;

  return (
    <InputBase
      fullWidth={true}
      className={[inputStyle.input].join(' ')}
      color='primary'
      {...rest}
    />
  );
}

(The error was triggered by the color attribute in this case.)

The correct way to approach this:

import InputBase, { InputBaseProps } from '@material-ui/core/InputBase';

import inputStyle from 'Input.module.scss';

export interface InputProps extends InputBaseProps {
  
}

export function Input(props: InputProps) {
  const { ...rest } = props;

  return (
    <InputBase
      fullWidth={true}
      className={[inputStyle.input].join(' ')}
      color='primary'
      {...rest}
    />
  );
}

Answer №2

According to the reference document provided by Material UI for Typography (https://material-ui.com/api/typography/)

{ h1: 'h1', h2: 'h2', h3: 'h3', h4: 'h4', h5: 'h5', h6: 'h6', subtitle1: 'h6', subtitle2: 'h6', body1: 'p', body2: 'p',}

variantMapping includes these mappings, so moving forward if you need to use <p> tags, you can specify the variant type as body1 or body2 instead of using the component prop.

Answer №3

Ever since I updated to

material-ui/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="52313d203712667c647c62">[email protected]</a>
and
<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="63171a13061000110a131723504d544d51">[email protected]</a>
, I have been facing this issue.

To temporarily silence the errors, I had to use component={'div' as any}. However, I believe there should be a more permanent solution on its way.

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

The scroll animation feature was not functioning properly in Next.js, however, it was working flawlessly in create react app

I recently transitioned a small project from Create React App (CRA) to Next.js. Everything is working as expected except for the scroll animations in Next.js, which are not functioning properly. There are no errors thrown; the animations simply do not occ ...

Struggled with setting up the WebSocket structure in typescript

Issue Running the code below results in an error: index.tsx import WebSocket from 'ws'; export default function Home() { const socket = new WebSocket('ws://localhost:1919/ws'); return ( <div>Home</div> ); } ...

The Aurelia application encounters a "Maximum call stack size exceeded" error while trying to bind FullCalendar

I am currently working on setting up a JQuery plugin (FullCalendar) within my Aurelia application, which is built using TypeScript. I am relatively new to web development and just trying to get a basic example up and running. To start off, I utilized this ...

What is the reason behind the required designation for the props onClose and onOpen in the SwipeableDrawer component of Material-UI?

It seems that the onOpen and onClose properties aim to incorporate elements of the Observer pattern. But why is it necessary for a client using the SwipeableDrawer component who does not wish to observe these events to still provide values for these prope ...

Discover the art of concurrently listening to both an event and a timer in JavaScript

Upon loading the page, a timer with an unpredictable duration initiates. I aim to activate certain actions when the countdown ends and the user presses a button. Note: The action will only commence if both conditions are met simultaneously. Note 2: To cl ...

Incorporate new markers into Google maps without the need to constantly initialize the map

My current goal is to have the user input a latitude and longitude into a text box, and then display a marker on the map for that location without needing to reinitialize the map each time. To start, I have set up my map like this: <script type="text/ ...

Is it possible to measure the CPU utilization in a TypeScript application programmatically?

Is there a method to calculate CPU usage as a percentage and record it in a file every 20 milliseconds? I'm interested in exploring different approaches for accomplishing this task. Your insights would be greatly appreciated! I've come across so ...

Have you checked the console.log messages?

As a newcomer to web development, I hope you can forgive me if my question sounds a bit naive. I'm curious to know whether it's feasible to capture a value from the browser console and use it as a variable in JavaScript. For instance, when I enco ...

The POST method functions properly in the local environment, however, it encounters a 405 (Method Not Allowed) error in the

After testing my code locally and encountering no issues, I uploaded it to Vercel only to run into the error 405 (Method Not Allowed) during the POST method. Despite checking everything thoroughly, I'm unable to find a solution on my own. Your assista ...

In the `angular-daterangepicker.js` file, add the option "Single Date" to the list of available ranges

I'm currently working on implementing a new feature that is similar to the "Custom Range" option, but with a twist. I want to provide users with the ability to choose only one date, much like a "Single Date Picker". By adding this new option under "Cu ...

Updating NPM packages versions is currently restricted

I'm in the process of creating a Next.JS application using create-next-app. However, I've noticed that in the package.json file it lists the following dependencies: "eslint": "8.43.0", "eslint-config-next": &quo ...

Personalizing the React Bootstrap date picker

I am currently working on customizing the react-bootstrap-daterangepicker to achieve a specific look: My goal is to have distinct background colors for when dates are selected within a range and when the user is hovering over dates to make a selection. I ...

Employ CSS flexbox and/or JavaScript for creating a customizable webpage

I am in the process of developing a basic IDE for an educational programming language that has similarities to Karel the Dog. One major issue I am encountering is creating the foundation HTML page. The IDE consists of 4 main areas: Toolbox (contains but ...

Creating Custom Filters in Angular using Functions

Attempting to filter ng-repeat using a function instead of an actual filter has presented some challenges. The code snippet below demonstrates the attempt: <tr ng-repeat="(key, value) in dataObj| filter:dataFilter"> The intention is to define dataF ...

Sinon - observing the constructor function

While I've come across a few related inquiries, none seem to address what I am specifically looking to achieve. My goal is to monitor a constructor method in such a way that when an object created with the constructor calls this method from a differe ...

When the height of the window decreases, scrolling is not implemented

Having trouble adjusting the height of my Responsive Modal when the window height decreases. The content is slipping under the window and the scroll bar isn't adjusting accordingly. It seems like the nested div structure is causing issues. https://i.s ...

Guide to selecting a specific year on a calendar using Selenium with JavaScript

While attempting to create a Selenium test using JavaScript, I encountered an issue with filling in calendar data through a dropdown menu: const {Builder, By, Key} = require('selenium-webdriver') const test2 = async () => { let driver = awa ...

The Art of Validating Configurations Using io-ts

I have recently switched to using io-ts instead of runtypes in a fresh project. In terms of configuration validation, my approach involves creating an object that specifies the types for each part of the config; const configTypeMap = { jwtSecret: t.str ...

Sending data to Layout for customizable routes (App Router) in Next.js version 13

Looking to pass props to the Layout component for dynamic routes in my project structure: /app -/(site) --/layout.tsx --/page.tsx --/[slug]/page.tsx --/[slug]/layout.tsx In the site layout: export default async function IndexRoute({ children }: { chil ...

Browser displaying a CSS error: "Invalid property name" while applying pseudo-element :after

I encountered an issue in Chrome and Explorer while attempting to set a CSS property for a pseudo element :after. (I'm trying to create a styled burger nav icon) The error message I received was: 'Unknown property name' This happened wh ...