如何使用Typescript扩展Material-UI主题? [英] How to extend Material-UI Theme with Typescript?

查看:92
本文介绍了如何使用Typescript扩展Material-UI主题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Typescript总是抱怨调色板中缺少某些属性.如果添加//@@ ts-ignore ,我的应用程序运行正常,但显然我想避免这种情况.我是Typescript的新手,这是我尝试过的.

Typescript is always complaining about certain properties missing in the palette. My app works just fine if I add //@ts-ignore, but I obviously want to avoid that. I'm new to Typescript and here is what I've tried.

import createMuiTheme, { ThemeOptions, Theme } from '@material-ui/core/styles/createMuiTheme';
import { PaletteOptions } from '@material-ui/core/styles/createPalette';

interface IPaletteOptions extends PaletteOptions {
    chip: {
      color: string,
      expandIcon: {
        background: string,
        color: string,
      },
    },
}
interface ITheme extends Theme {
  palette: IPaletteOptions,
}

const theme: ITheme = createMuiTheme({
  typography: {
    fontWeightMedium: 600,
    fontFamily: ['Open Sans', 'Arial', 'sans-serif'].join(','),
  },
  palette: {
    primary: {
      main: '#43C099',
    },
    secondary: {
      main: '#7AF3CA',
    },
    chip: {
      color: '#C2C3C6',
      expandIcon: {
        background: '#808183',
        color: '#FFFFFF',
      },
    },
  },
} as ThemeOptions);

这会引发错误,

Type 'Theme' is not assignable to type 'ITheme'.
  Types of property 'palette' are incompatible.
    Property 'chip' is missing in type 'Palette' but required in type 'IPaletteOptions

这对我来说是一个令人困惑的错误,因为我在任何地方都没有使用 Palette 类型.

This is a confusing error for me, because type I'm not using the type Palette anywhere.

如何在此处适当扩展调色板?

How can I properly extend the palette here?

推荐答案

解决方案

import createMuiTheme, { Theme, ThemeOptions } from "@material-ui/core/styles/createMuiTheme";
import { Palette } from "@material-ui/core/styles/createPalette";

interface IPalette extends Palette {
  xxx: {}
}
interface ITheme extends Theme {
  palette: IPalette;
}
interface IThemeOptions extends ThemeOptions {
  palette: IPalette;
}

const theme = createMuiTheme({
  palette: {
    ...
    xxx: {}                                        // Type been checked
  }
} as IThemeOptions)                                // Use customized ThemeOptions type

const useStyles = makeStyles((theme: ITheme) => ({ // Use customized Theme type
  root: {
    color: theme.palette.xxx                       // Work with no type error
  }
}));


引用

如果我们查看 createMuiTheme.d.ts

import { Palette, PaletteOptions } from './createPalette';

export interface ThemeOptions {
  palette?: PaletteOptions;
  ...
}

export interface Theme {
  palette: Palette;
  ...
}

export default function createMuiTheme(options?: ThemeOptions, ...args: object[]): Theme;

我们会发现 Theme ThemeOptions 发挥着不同的作用.

We would find that Theme and ThemeOptions play a different role.

  • 主题:返回类型
  • ThemeOptions:参数类型

这篇关于如何使用Typescript扩展Material-UI主题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆