1

我正在使用 React、React Admin、Babel、TypeScript 和 Webpack 建立一个项目。我使用的编辑器是 VSCode。

我正在尝试使用新的 Material UI 样式解决方案,然后特别是 Styled Components API。

我已经配置了 TSLint,因此需要将 a 添加typedef到变量声明中。

当我编写以下代码时:

const StyledButton = styled(Button)({
  backgroundColor: 'yellow',
  height: 10,
  width: 80,
});

TSLint 抛出以下错误:expected variable-declaration: 'StyledButton' to have a typedef (typedef)tslint(1). 请注意,Button我传递给styled()的是来自 Material UI 的组件:

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

然后,当我将鼠标悬停在上面时,StyledButton我看到以下内容:

在此处输入图像描述

所以基本上 VSCode 告诉我StyledButton变量的类型,即React.ComponentType. 因此,如果我将代码更新为此:

const StyledButton: React.ComponentType = styled(Button)({
  backgroundColor: 'yellow',
  height: 10,
  width: 80,
});

我没有任何错误。伟大的!

但是现在我的问题开始了:当我将 更改Button为实际的 HTML 元素时button

const StyledButton: React.ComponentType = styled('button')({
  backgroundColor: 'yellow',
  height: 10,
  width: 80,
});

我的编辑器抛出以下错误:

Type 'ComponentType<never>' is not assignable to type 'ComponentType<{}>'.
  Type 'ComponentClass<never, any>' is not assignable to type 'ComponentType<{}>'.
    Type 'ComponentClass<never, any>' is not assignable to type 'ComponentClass<{}, any>'.
      Types of property 'getDerivedStateFromProps' are incompatible.
        Type 'GetDerivedStateFromProps<never, any> | undefined' is not assignable to type 'GetDerivedStateFromProps<{}, any> | undefined'.
          Type 'GetDerivedStateFromProps<never, any>' is not assignable to type 'GetDerivedStateFromProps<{}, any>'.
            Types of parameters 'nextProps' and 'nextProps' are incompatible.
              Type 'Readonly<{}>' is not assignable to type 'never'

当我删除typedef并再次悬停时StyledButton,我看到以下内容:

在此处输入图像描述

所以 VSCode 告诉我类型已更改为React.ComponentType<never>. 让我们将我的代码更新为:

const StyledButton: React.ComponentType<never> = styled('button')({
  backgroundColor: 'yellow',
  height: 10,
  width: 80,
});

错误消失了,很好!让我们使用StyledButton

<StyledButton>
  I'm a button
</StyledButton>

这会引发另一个错误:

This JSX tag's 'children' prop expects type 'never' which requires multiple children, but only a single child was provided.ts(2745)

我做错了什么还是?StyledButton当我实际使用组件时,如何正确键入而不出错?

我也在 GitHub 上发布了这个问题,但不幸的是它被关闭了:https ://github.com/mui-org/material-ui/issues/14898

如果您需要更多信息,请让我知道并提前致谢!

4

0 回答 0