웹사이트 검색

reactjs - Typescript 오류: 속성이 해당 타입에 존재하지 않는다고 표시됨


참고! 아래 선언에서 'theme: any'를 사용하여 문제를 완화할 수 있었지만, 더 나은 방법을 선호합니다.

저는 프론트엔드에 React (v17.0.2)를 사용하고 있으며 material-ui (v5.0.0)를 사용하고 있는데 다음과 같은 오류가 발생합니다:

속성 'palette'는 'Theme' 유형에 존재하지 않습니다.

내가 내 테마에 이렇게 접근하려고 할 때마다:

import { useTheme } from '@emotion/react';

export default function MyComponent() {

    const theme = useTheme()

    return (
        <Box
            sx={{
                backgroundColor: theme.palette.mode === 'dark' ? 'primary.dark' : 'primary',
            }}
        ></Box>
    );
}

선언문 아래에 console.log(theme)로 객체를 기록했더니 내 테마가 성공적으로 기록되었습니다. 그래서 객체는 존재하지만 위와 같이 접근할 수 없습니다. 기록된 내용 중 일부는 다음과 같습니다:

{breakpoints: {…}, direction: 'ltr', components: {…}, palette: {…}, spacing: ƒ, …}
  > breakpoints: {keys: Array(5), ...}
  > components: {MuiTypography: {…}, ...}
  direction: "ltr"
  > mixins: {toolbar: {...}}
  > palette: {mode: 'dark', ...}
  ...

또한, 저는 'Theme' 타입이 위치한 파일과 'palette' 속성이 분명히 존재하는 파일도 찾았습니다. 파일의 일부분은 다음과 같습니다:

export interface Theme extends SystemTheme {
  mixins: Mixins;
  components?: Components;
  palette: Palette;
  shadows: Shadows;
  transitions: Transitions;
  typography: Typography;
  zIndex: ZIndex;
  unstable_strictMode?: boolean;
}

저도 다음과 같이 Theme를 가져와서 사용해 보았습니다:

import { Theme } from '@mui/material/styles';
...
const theme: Theme = useTheme()
...

그리고 이것은 나에게 새로운 오류를 주었습니다 ("theme" 변수를 밑줄 친 상태로):

타입 'Theme'에는 타입 'Theme'에서 다음 속성이 누락되어 있습니다: mixins, palette, shadows, transitions, 그리고 6개 더.

저도 이렇게 해봤어요:

import { Theme } from '@mui/material/styles';
...
const theme = useTheme<Theme>()
...

그리고 이것은 나에게 새로운 오류를 주었습니다 (useTheme<Theme>()에서 'Theme'를 밑줄 친 상태로)

0개의 타입 인수가 예상되었지만 1개를 받았습니다.

그리고 또한

속성 'palette'는 'Theme' 유형에 존재하지 않습니다.

저는 타입스크립트에 새로워서, 어떤 도움이라도 감사히 받겠습니다.

수정 답은 Alex Wayne 덕분에 얻었고 (처음에 답을 오해했다면 아마도 windowsill 덕분이기도 함). 작동한 코드는 다음과 같습니다:

import { useTheme, Theme } from '@mui/material';
const theme: Theme = useTheme()
<Box sx={{backgroundColor: theme.palette.mode}}></Box>

답변 #1

적절한 타입 검사를 얻기 위해 MUI의 인터페이스로 emotion Theme 인터페이스를 확장할 수 있습니다.

import { Theme as MuiTheme } from "@mui/material/styles";

declare module '@emotion/react' {
  export interface Theme extends MuiTheme {}
}

https://emotion.sh/docs/typescript#define-a-theme 에 명시된 대로

답변 #2

  • `@emotion/react`는 같은 패키지의 `useTheme()`에서 반환되는 `Theme` 타입을 내보냅니다.
  • `@mui/material/styles`는 동일한 패키지의 `createTheme`에서 반환되는 `Theme` 타입을 내보냅니다.
  • 이것들은 같은 종류가 아니다.

각 패키지에는 같은 이름이 있지만, 전혀 관련이 없습니다.

이것이 실패하는 이유입니다:

import { useTheme } from '@emotion/react';
import { Theme } from '@mui/material/styles';
const theme: Theme = useTheme()
// Type 'Theme' is missing the following properties from type 'Theme': mixins, palette, shadows, transitions, and 2 more.(2740)

놀이터

하지만 이것은 성공한다.

import { useTheme, Theme } from '@emotion/react';
const theme: Theme = useTheme()

놀이터

어느 것을 사용하려는지 정확히는 모르겠지만, 여기에 emotion 테마에 대한 문서가 있고, 여기에 Material UI 테마에 대한 문서가 있습니다. 이들은 별개의 것이며, 각각의 의도된 용도에 맞게 사용해야 합니다.

관련기사