首页 > 解决方案 > TypeScript 错误:类型“字符串”不可分配给排版的类型

问题描述

我正在尝试将 Material-ui 中的 Typography 组件与 TypeScript 一起使用,但我收到了这个奇怪的错误

TypeScript 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;

这是我的组件的样子

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>
);

我无法理解为什么道具"p"的价值不可接受。component我尝试使用"h1"and "h2"以同样的方式失败,显然,官方演示也使用了字符串。

有什么我遗漏的吗?,我不想用 忽略这个// @ts-ignore,但想解决这个问题。

标签: javascriptreactjstypescriptmaterial-ui

解决方案


如果在 2021 年发生这种情况,问题是我正在传播HTMLAttributes针对 的输入InputBase,而我应该正确传播InputBaseProps

在我的例子中,它与输入相关,但可以为每个组件复制相同的内容:只要您使用材质 UI 组件,您应该提供它要求的属性,并在使用/扩展它们时正确设置正确的道具类型。

给出错误的示例:

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}
    />
  );
}

(在这种情况下,出现了错误color

正确的方法:

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}
    />
  );
}

推荐阅读