为什么在声明了属性后仍继续使属性变得不确定?

时间:2019-09-04 06:18:55

标签: reactjs typescript material-ui

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

我尝试重现问题in codesandbox,但没有出现错误。但我将解释它在本地计算机上的显示方式。

在我的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中自定义类型的类型,尽管我没有对该文件出错。但是将其设置为Theme类型并不能消除错误。

1 个答案:

答案 0 :(得分:0)

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

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

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