概要
UdemyでReactの講座を受けていた際、写経したらエラーが出たので共有します
該当講座
こちらの講座の「32.MUIでメニューの見た目を作ろう」で発生しました。
コード
DailySummary.tsx
<Typography
color={(theme) => theme.palette.incomeColor.main}
textAlign="right"
fontWeight="fontWeightBold"
sx={{ wordBreak: "break-all" }}
>
¥500
</Typography>
出ていたエラー🤢
ERROR in src/components/DailySummary.tsx:19:17
TS2769: No overload matches this call.
Overload 1 of 2, '(props: { component: ElementType<any, keyof IntrinsicElements>; } & TypographyOwnProps & CommonProps & Omit<any, "border" | ... 112 more ... | "variantMapping">): Element | null', gave the following error.
Type '(theme: any) => any' is not assignable to type '(string & {}) | "primary" | "secondary" | "success" | "error" | "info" | "warning" | "textDisabled" | "textPrimary" | "textSecondary" | undefined'.
Overload 2 of 2, '(props: DefaultComponentProps<TypographyTypeMap<{}, "span">>): Element | null', gave the following error.
Type '(theme: any) => any' is not assignable to type '(string & {}) | "primary" | "secondary" | "success" | "error" | "info" | "warning" | "textDisabled" | "textPrimary" | "textSecondary" | undefined'.
17 | </Typography>
18 | <Typography
> 19 | color={(theme) => theme.palette.incomeColor.main}
| ^^^^^
20 | textAlign="right"
21 | fontWeight="fontWeightBold"
22 | sx={{ wordBreak: "break-all" }}
ERROR in src/components/DailySummary.tsx:19:25
TS7006: Parameter 'theme' implicitly has an 'any' type.
17 | </Typography>
18 | <Typography
> 19 | color={(theme) => theme.palette.incomeColor.main}
| ^^^^^
20 | textAlign="right"
21 | fontWeight="fontWeightBold"
22 | sx={{ wordBreak: "break-all" }}
vscode上では「パラメーター 'theme' の型は暗黙的に 'any' になります」とも出ていました。
原因
Typographyコンポーネントのcolorプロパティにテーマ関数を使用しようとしているため。
Typographyプロパティ内のcolorは文字列かカスタムカラー名しか使えないようです。
解決
sxプロパティを使い、sxプロパティ内でcolorを定義することで対応した。
DailySummary.tsx
<Typography
sx={{
color: (theme) => theme.palette.incomeColor.main,
textAlign: "right",
fontWeight: "fontWeightBold",
wordBreak: "break-all",
}}
>
¥500
</Typography>