Passing an object to createMuiTheme in Typescript and Material UI

Struggling with TypeScript and Material UI integration, I'm puzzled by the issue of passing an object to createMuiTheme.

This code snippet works perfectly:

const themeConfig = createMuiTheme({
  palette: {
    primary: green,
    secondary: purple,
    type: 'light'
  }
});

But, this following code does not work (!):

const themeObject = {
  palette: {
    primary: green,
    secondary: purple,
    type: 'light'
  }
};

const themeConfig = createMuiTheme(themeObject);

An error message states that 'palette.type = 'light' (string)' is not assignable to 'palette.type = 'light' | 'dark' | undefined'. This error is truly perplexing.

Argument of type '{ palette: { primary: { 50: "#e8f5e9"; 100: "#c8e6c9"; 200: "#a5d6a7"; 300: "#81c784"; 400: "#66bb6a"; 500: "#4caf50"; 600: "#43a047"; 700: "#388e3c"; 800: "#2e7d32"; 900: "#1b5e20"; A100: "#b9f6ca"; A200: "#69f0ae"; A400: "#00e676"; A700: "#00c853"; }; secondary: { ...; }; type: string; }; }' is not assignable to parameter of type 'ThemeOptions'.
  The types of 'palette.type' are incompatible between these types.
    Type 'string' is not assignable to type '"light" | "dark" | undefined'.ts(2345)

Answer №1

Check out the segment "Utilizing createStyles for type narrowing" in the guide available at https://material-ui.com/guides/typescript/.

You have the option to directly input the settings as arguments in createMuiTheme():

const themeOptions = createMuiTheme({
  palette: {
    primary: green,
    secondary: purple,
    type: 'light'
  }
});

Answer №2

In case you're curious, I found that using an object to populate `createMuiTheme({})` works in JavaScript, although not in TypeScript - I did a test to confirm this.

It's important to note that it requires an empty object as the starting point, and you shouldn't initialize it as a `const` since you'll be adding values to it right away.

import { createMuiTheme } from '@material-ui/core/styles';
import { blue, green, pink, yellow } from '@material-ui/core/colors';

let theme = {};
const themeObject = {
  palette: {
    primary: {
      main: blue[500],
    },
    secondary: {
      main: green[500],
    },
    info: {
      main: pink[400],
    },
    warning: {
      main: yellow[900],
    },
  },
  overrides: {
    MuiCssBaseline: {
      '@global': {
        body: {
          backgroundImage: `url("/background-image.jpg")`,
          backgroundAttachment: `fill`,
          backgroundSize: `cover`,
          backgroundPosition: `0 0`,
          backgroundRepeat: `no`,
        },
      },
    },
  },
};

export default theme = createMuiTheme(themeObject);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for incorporating a class as a data type in a variable using TypeScript

I am finding it a bit challenging to understand how to implement OOP in TypeScript after being familiar with PHP. 1 - Is it possible to use a class as a type without needing to populate all the attribute values? 2 - Must I always create an interface to d ...

Is it possible to utilize MUI without the need for @emotion/react and @emotion/styled dependencies?

Whenever I attempt to integrate MUI into my React JS application by running npm install @mui/material, I encounter some errors: Compiled with problems:X ERROR in ./node_modules/@mui/material/node_modules/react-transition-group/esm/CSSTransition.js 5:0-47 ...

The panning functionality on Android devices within the Firefox browser is currently experiencing issues with both panstart and pan

Currently, I am collaborating on an Angular7 project and utilizing hammerjs version 2.0.1. One of the tasks at hand is to allow panning functionality on a map for mobile devices. After testing on various android devices, I noticed that it performs well on ...

Choose a specific interface in Typescript

I am interested in developing a React alert component that can be customized with different message colors based on a specific prop. For example, I envision the component as <alert id="component" info/> or <alert id="component" ...

What exactly is the function of the NextPage feature in Next.js?

Recently, I began incorporating TypeScript into my Next project. Could someone clarify the purpose of the following code snippets for me? import { NextPage } from 'next'; export const Page: NextPage = () => {} After reviewing the documentation ...

Creating a Typescript interface for a anonymous function being passed into a React component

I have been exploring the use of Typescript in conjunction with React functional components, particularly when utilizing a Bootstrap modal component. I encountered some confusion regarding how to properly define the Typescript interface for the component w ...

Having trouble loading AngularJS 2 router

I'm encountering an issue with my Angular 2 project. Directory : - project - dev - api - res - config - script - js - components - blog.components.js ...

What are the steps for integrating angular2 starter with express?

Can someone explain how to integrate the following Angular starter template into an Express framework? https://github.com/gdi2290/angular-starter I am able to start the webpack dev server without any issues, but I would like to utilize additional librari ...

Having trouble with JSON parsing in Promise execution

I am in the process of developing a Promise with the objective of adding up any numbers discovered within an array or JSON object. The add() function is designed to receive a series of URLs as a string input and calculate the total sum of those URLs. Her ...

The label for the Material UI TextField is visible on top of the popper

I am currently using Material-UI and have a form that includes TextFields. https://i.sstatic.net/8mSjX.png One issue I am experiencing is that when I activate my popper, the labels from the form textfields overlay the popper, but not the field itself. I& ...

Using a template literal with the keyof operator as an interface property

Imagine a scenario where we have a basic interface: interface Schedule { interval: "month" | "day"; price: number; } We can create a template-literal type with TypeScript version 4.4: type PrefixedScheduleKey = `schedule__${keyof S ...

When organizing Node.js express routes in separate files, the Express object seamlessly transforms into a Router object for efficient routing

I am currently working on a Node.js application with Express. I organize my routes using tsoa, but when I introduce swagger-ui-express to the project, an error occurs Error: TypeError: Router.use() requires a middleware function but got undefined Here is ...

Querying subdocuments within an array using MongoDB's aggregation framework

Currently, I'm facing a challenge while developing a statistics dashboard for a meditation app. I'm struggling with creating a MongoDB query to fetch the most popular meditations based on user progress. The key collections involved are users and ...

SplitChunks in Webpack 4 helps to cache modules so they do not need to be reprocessed

Currently, I am working on a TypeScript project that utilizes node packages and webpack for compiling and bundling. The folder structure of my project is as follows: Scripts App Various Modules Utility Various Utility components a ...

Develop a simulated version that does not include all the functionalities of the primary service

Let's imagine a scenario where there is an OriginalService class with various methods class OriginalService { method1() { } method2() { } method3() { } .. } Now, suppose we need to create a mock of OriginalService that will only be used with ...

MSW is not effective when utilized in functions within certain contexts

Trying to intercept a post request using MSW for result mocking. A handleLogin function is located within a context, but MSW cannot recognize handleLogin as a function. An error occurs: ReferenceError: handleLogin is not a function. If the API call is made ...

Is it possible for a redis client to function without having a redis datastore installed?

Currently in my node web server, I am utilizing the npm module known as redis. Upon executing my code... const client = redis.createClient(); client.on("error", function (err) { console.log("Error " + err); }); client.hmset(["key", "test keys 1", "t ...

Is there a way to hide the row select option for individual rows in MUIDatatables without affecting the multiple row select options?

Is there a way to hide the checkbox in the header row that allows selection of all rows at once? I prefer to manually select multiple options by clicking on each individual row. Can the row select option be hidden? https://i.sstatic.net/dfiJQ.png ...

What is the best way to prevent numbers (even in String format) in a MaterialUI TextField?

Check out the following code snippet: <Grid item lg={6} md={6} xs={12} > <TextField fullWidth type={'text'} label="Product Color" value={productColor} onChange={(e) => setProductColor(e.target.value)} /> </Grid> ...

Promise.allSettled() - Improving resilience through retry mechanisms for concurrent asynchronous requests

TL;DR: I'm seeking advice on how to handle multiple promise rejections and retry them a specified number of times when using Promise.allSettled() for various asynchronous calls. Having come across this article: I was intrigued by the following state ...