The absence of type-safety in the MUI System sx is a glaring issue

I want to ensure that the TypeScript compiler can identify typos in my MUI System sx props:

import { Box, SxProps, Theme, Typography } from '@mui/material'
    
const sxRoot: SxProps<Theme> = {
  width: '100vw',
  height: '100vh',
  diplay: 'grid', // <-- typo should lead to TS compile-time error
  placeItems: 'center',
}
    
export const App = () => (
  <Box sx={sxRoot}>
    <Typography>{'Hello World'}</Typography>
  </Box>
)

Feel free to explore my sample project using the Vite template along with MUI 5.15.19.

What have I overlooked?

Answer №2

If you want to identify typos in the MUI System sx props during compilation using TypeScript, it's important to activate strict type checking for the sx prop. By default, the sx prop permits any valid CSS properties, including unknown or misspelled ones.

To enforce strict type checking, utilize the SystemStyleObject type from @mui/system instead of SxProps<Theme>. Below are some code snippets that can help rectify this issue:

Update the sxRoot type to incorporate SystemStyleObject:

import { Box, Typography } from '@mui/material';
import { SystemStyleObject } from '@mui/system';

const sxRoot: SystemStyleObject = {
  width: '100vw',
  height: '100vh',
  diplay: 'grid', // <-- This will now lead to a TS compile-time error
  placeItems: 'center',
};

export const App = () => (
  <Box sx={sxRoot}>
    <Typography>{'Hello World'}</Typography>
  </Box>
);

By utilizing SystemStyleObject, TypeScript will ensure stringent typing for the sx prop and catch any erroneous or unidentified properties at compile time.

Additionally, ensure you have all the required dependencies installed for this solution to function correctly.

npm install @mui/material @mui/system @emotion/react @emotion/styled

Subsequently, update the tsconfig.json file with these settings:

{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitAny": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "noImplicitReturns": true
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

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

Conditional Rendering with Next.js for Smaller Displays

I've implemented a custom hook to dynamically render different elements on the webpage depending on the screen size. However, I've noticed that there is a slight delay during rendering due to the useEffect hook. The conditionally rendered element ...

Combining multiple values in a single field using Material UI DataGrid ValueFormatter

Hello everyone, I am currently working with material UI DataGrid and dealing with the following code snippet: const columns = [ { field: 'date', headerName: 'Date',flex: 1}, { field: 'user_id', headerName: 'Shop&a ...

The .Muimenu-root component is malfunctioning, causing issues with the Menu MUI component and styled-components

My approach involves applying styles to the root level using the Menu component from MUI, in conjunction with styled-components. import * as React from "react"; import Button from "@mui/material/Button"; import MenuItem from "@mui/ ...

"What is the significance of the .default property in scss modules when used with typescript

When dealing with scss modules in a TypeScript environment, my modules are saved within a property named default. Button-styles.scss .button { background-color: black; } index.tsx import * as React from 'react'; import * as styles from ' ...

The Angular project seems to be experiencing technical difficulties following a recent update and is

Recently, I made the transition from Angular 6 to 8 and encountered two warnings during the project build process that I can't seem to resolve. Despite searching online for solutions, nothing has worked so far. Any help would be greatly appreciated. ...

Something went wrong: Unable to access the properties of an undefined variable named 'gametitle'

I am able to see the variables on the html-page, but I encountered an error specifically with the value of the gametitle ERROR TypeError: Cannot read properties of undefined (reading 'gametitle') Below is the content of the ts-file: import { ...

Having trouble integrating Azure with my Ionic2/Angular2/Cordova app

I am currently developing with the Ionic2 Blank app template. I encountered an issue when trying to set up Azure using the following line of code in home.ts: import azureMobileClient from 'azure-mobile-apps-client'; . The deployment process wen ...

Can you explain the use of parentheses in a typescript type when defining a key?

Could someone provide an instance of an object that matches the TypeScript type below? I'm a bit confused because I've only worked with interfaces before and have only seen square brackets. type Hash = { (data: Uint8Array): Uint8Array blockLe ...

What is a sleek method for including a key and value pair to an object using an array?

In a project using angular2/typescript, I am working with an array of objects that contain key/value pairs from a database. These values are then displayed in a table on the UI using ag-grid-ng2. The table headers are dynamic and set in the database. One ...

Validating a field conditionally upon submission

Adding a required validation conditionally to the "imageString" field upon submission, but the expected required validation is not being set. Initializing the form. constructor(){ this.poeForm = this.fb.group({ imageString: [""], imageFileNam ...

Encountering a compiler error due to lack of patience for a promise?

In the current TypeScript environment, I am able to write code like this: async function getSomething():Promise<Something> { // ... } And later in my code: const myObject = getSomething(); However, when I attempt to use myObject at a later po ...

In order to resolve the issue in nextjs 13 where the argument is of type 'any[] | null' and cannot be assigned to the parameter of type 'SetStateAction<never[]>', a potential solution may involve explicitly checking for null values

My current project uses Next.js 13 and is based on the Supabase database. I am attempting to fetch data from Supabase and assign it to a variable using useState, but encountering the following error: Argument of type 'any[] | null' is not assigna ...

Due to a TypeScript error stating that the type '{ Id: number; Name: string; }' cannot be utilized as an index type, I am unable to assign a value for students at this time

I am facing an issue with defining a value for students in TypeScript. It is giving me an error saying that it can't be used as index type. Just to clarify, I have declared id as number (not Number) and Name as string (not String). import { Component ...

Challenge encountered with implementing Next-Auth's authorize function in TypeScript

Encountering a type error in the authorize function while using NextAuth with CredentialsProvider export const authOptions : NextAuthOptions ={ session : { strategy: "jwt" }, providers : [ CredentialsProvider({ async authorize( c ...

Alter the content of Material-UI ListItem when in hover or active state

Imagine a scenario where you have a side-bar navigation with the following component structure: <ListItem button dense component={CustomNavLink} to="/dashboard"> <ListItemIcon> <DashboardIcon /> </ListItemIcon ...

Is it possible to initialize multiple Observables/Promises synchronously in ngOnInit()?

I am relatively new to Angular/Typescript and facing a challenge. In my ngOnInit(), I am trying to fetch settings from my backend using a GET request. After that, I need to subscribe to an observable. The observable updates the widgets' content over t ...

The required and defaultValue attributes seem to be malfunctioning on my Textfield, although the placeholder feature is functioning properly

In the card below, I have implemented a simple edit functionality. Upon clicking edit, a textfield is supposed to appear for me to make changes and save them. However, I am facing issues with the required and defaultValue attributes in my Textfield, alth ...

How to customize the TransitionComponent of a Material-UI Snackbar to Slide

I am trying to modify the transition of the snackbar from Grow (which is the default behavior) to Slide Up on a Customized snackbar. However, I am facing challenges in achieving this: import React from 'react'; import PropTypes from 'prop-t ...

Angular HttpInterceptor failing to trigger with nested Observables

Utilizing a HttpInterceptor is essential for adding my Bearer token to all calls made to my WebApi. The interceptor seamlessly functions with all basic service calls. However, there is one specific instance where I must invoke 2 methods and utilize the re ...

What is the best way to sort an array of objects based on their properties?

I am working with an array of objects: let response = [{"id": 1, "name": "Alise", "price": 400, "category": 4}]; In addition to the array of objects, I have some arrays that will be used for filtering: let names = ["Jessy", "Megan"]; let prices = [300, ...