首页 > 解决方案 > 为什么我在已经声明属性时继续获取未定义的属性?

问题描述

我的问题是关于我需要切换它的主题,但我遇到了类型问题。我不确定它是否与我的打字稿配置或我的代码有关。

我试图在代码沙箱中重现该问题但没有出现错误。但我将解释它在我的本地机器上的显示方式。

在我的hooks.ts文件中line 12,我收到一条错误消息type,即使存在也不存在。

 TS2339: Property 'type' does not exist on type 'PaletteOptions | undefined'.

而且line 24我收到错误说

[0]       TS2345: Argument of type '{ palette: { type: string; } | { type: string; primary?: SimplePaletteColorOptions | Partial<Color> | undefined; secondary?: SimplePaletteColorOptions | Partial<Color> | undefined; ... 9 more ...; getContrastText?: ((background: string) => string) | undefined; }; ... 10 more ...; zIndex?: Partial<...> | undefined; }' is not assignable to parameter of type 'SetStateAction<ThemeOptions>'.
[0]   Type '{ palette: { type: string; } | { type: string; primary?: SimplePaletteColorOptions | Partial<Color> | undefined; secondary?: SimplePaletteColorOptions | Partial<Color> | undefined; ... 9 more ...; getContrastText?: ((background: string) => string) | undefined; }; ... 10 more ...; zIndex?: Partial<...> | undefined; }' is not assignable to type 'ThemeOptions'.
[0]     Types of property 'palette' are incompatible.
[0]       Type '{ type: string; } | { type: string; primary?: SimplePaletteColorOptions | Partial<Color> | undefined; secondary?: SimplePaletteColorOptions | Partial<Color> | undefined; error?: SimplePaletteColorOptions | ... 1 more ... | undefined; ... 8 more ...; getContrastText?: ((background: string) => string) | undefined; }' is not assignable to type 'PaletteOptions | undefined'.
[0]         Type '{ type: string; }' is not assignable to type 'PaletteOptions'.
[0]           Types of property 'type' are incompatible.
[0]             Type 'string' is not assignable to type '"light" | "dark" | undefined'.

我不确定是否是因为我使用ThemeOptions自定义类型的类型,theme.ts尽管我在该文件上没有收到错误。但是将其设置为Themetype 并不能消除错误。

标签: reactjstypescriptmaterial-ui

解决方案


它无法识别 PaletteType 的任何字符串:

import { PaletteType } from '@material-ui/core';

const updatedTheme = {
  ...theme,
  palette: {
    ...theme.palette,
    type: (type === "light" ? "dark" : "light") as PaletteType
  }
};

推荐阅读