I have added a custom object named fTokens
to the MUI theme via Module augmentation in TypeScript
This is how my theme.d.ts
looks like
declare module "@mui/material/styles" {
interface FPalette { ...
}
interface FTokens { ...
}
interface FSpacing { ...
}
interface Theme {
fPalette: FPalette;
fTokens: FTokens;
fSpacing: FSpacing;
}
interface ThemeOptions {
fPalette: Partial<FPalette>;
fTokens: Partial<Tokens>;
fSpacing: Partial<FSpacing>;
}
}
And I am trying to pass a custom prop rowId
to TableRow
of MUI
import MUITableRow, { TableRowProps as MUITableRowProps } from "@mui/material/TableRow";
import { styled } from "@mui/system";
interface TableRowProps {
rowId: number;
}
const TableRow = styled(MUITableRow)<TableRowProps>(({ theme }) => ({
backgroundColor: theme.fTokens.surfaceHigh,
}));
export default TableRow;
I am getting TypeScript error as Property 'fTokens' does not exist on type 'Theme'.ts(2339)
UPDATE – I tried Type assertion using as
keyword that is working for me but I don’t know if this is the most elegant way to solve this?
const TableRow = styled(MUITableRow)<TableRowProps>(({ theme, rowId }) => ({
backgroundColor:
rowId % 2 === 0
? (theme as Theme).fTokens.surfaceHigh
: (theme as Theme).fTokens.surfaceHighest,
}));
2
Answers
The
theme
has the typeTheme
, which is the same type that your should probably have declared in theThemeProvider
. You can read the type declaration in the official repo here https://github.com/mui/material-ui/blob/master/packages/mui-material/src/styles/createTheme.d.ts#L28-L36As you can tell, there are no
fTokens
according to the type declaration file, therefore throwing the error.What you want to do to fix it is to start from the
ThemeProvider
to provide the color to the appropriate property, for example —palette
, THEN you can theme/styled theTableRow
with the color you just added to yourThemeProvider
.Here’s example code —
Documentation about
styled
utility here: https://mui.com/system/styled/Random test in Codesandbox that doesn’t throw error (except
<tr>
should not be child of<div>
) https://codesandbox.io/s/determined-kowalevski-ppm6zh?file=/src/App.tsxtry import styled from ‘@mui/material/styles’, not ‘@mui/system’
import { styled } from '@mui/material/styles';
doc: https://mui.com/system/styled/#import-path