首页 > 解决方案 > React/TS/material-ui 使用变量作为网格属性的值会引发错误:“没有重载匹配”和“类型'数字'不可分配给类型......”

问题描述

tl;dr:xs当在 JSX中使用变量作为网格属性的值时,material-ui 会引发 TS 错误


我正在使用 React/TypeScript 在 material-ui 中实现网格

我希望特定元素的宽度取决于该元素的数量。

这是一个简单的计算,输出 12 到 4 之间的整数:

const sheets = [0, 1, 2];
const sheetColWidth = sheets.length > 3 ? 3 : 12 / sheets.length;

但是当我使用 sheetColWidth (value 1, 2, 3or 4, of type number) 作为网格xs属性的值时,TS 会抛出一个错误:

No overload matches this call.
  Overload 1 of 2, '(props: { component: ElementType<any>; } & Partial<Record<Breakpoint, boolean | 1 | 6 | 3 | 5 | 7 | 10 | "auto" | 2 | 4 | 8 | 9 | 11 | 12>> & { ...; } & CommonProps<...> & Pick<...>): Element', gave the following error.
    Type 'number' is not assignable to type 'boolean | 1 | 6 | 3 | 5 | 7 | 10 | "auto" | 2 | 4 | 8 | 9 | 11 | 12 | undefined'.
  Overload 2 of 2, '(props: DefaultComponentProps<GridTypeMap<{}, "div">>): Element', gave the following error.
    Type 'number' is not assignable to type 'boolean | 1 | 6 | 3 | 5 | 7 | 10 | "auto" | 2 | 4 | 8 | 9 | 11 | 12 | undefined'.  TS2769

我在 Codesandbox 上有一个简化的示例:

https://codesandbox.io/s/loving-dust-cli52

(这没有附加样式,因为它们不相关)

当你加载它时,它似乎渲染得很好,但片刻之后,xsL.18 上的属性得到一个红色的错误下划线,并将鼠标悬停在它上面会显示错误。

在我的应用程序中,该应用程序只是因 TS 错误而崩溃。

用允许的数字替换sheetColWidthL.18 上的,错误消失,一切都很好。

有点混淆,因为变量的值是 Grid 接口中枚举的允许值之一。

我为它尝试了字符串插值,但后来因为它是一个字符串而被拒绝,因为它应该是:

xs={`${sheetColWidth}`}

我尝试将值转换为字符串然后再转换为数字 - 这没有改变,而且非常正确:

const sheetColWidth = parseInt(sheets.length > 3 ? 3 : 12 / sheets.length + '');

我难住了。

任何见解都非常感谢。

标签: reactjstypescripttypesmaterial-ui

解决方案


您还可以使用库本身中可用的类型:

import { Grid, GridSize } from "@material-ui/core";
// ...
const sheetColWidth: Gridsize = 1;

推荐阅读