ウェブサイト検索

typescript - Emotion の Theme 型にプロパティは存在しません


私は問題に直面しました。テーマオブジェクトからいくつかのパラメータを読み取ろうとしたり、それを分解しようとすると、エラーが発生します。

型 'Theme' にプロパティ 'X' は存在しません。

types.d.ts ファイルを作成してそこに追加しましたが、役に立ちません。

import '@emotion/react';
import { themeConfig } from './lib/theme';

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

私の「カスタムプロバイダー」のコード

// Import modules
import React from 'react';
import {
  css,
  Global, 
  Theme,
  ThemeProvider
} from '@emotion/react';

// Init Theme Config
export const themeConfig = {
  typography: {...},
  palette: {...}
};

interface Props {
  theme: Theme;
}

// Create custom ThemeProvider
export const Provider: React.FC<Props> = ({ children, theme = themeConfig }) => (
  <ThemeProvider theme={ theme }>
    <Global
      styles={(theme) => {
        console.log(theme.palette); <- Here an error
        return css``;
      }}
    />
    { children }
  </ThemeProvider>
);

更新:

こんなふうに change types.d.ts の問題を解決しました

type ThemeConfig = typeof themeConfig;
declare module '@emotion/react' {
  export interface Theme extends ThemeConfig {}
}

回答 #1

よりクリーンな方法は、TSの型を定義して直接拡張することです。

まず、テーマのフォーマットを定義するための TS タイプを作成します。それは任意のフォーマットにすることができます

type MyThemeFormat = {
  fontStyle: 'sans' | 'serif'
  colorMode: 'dark' | 'light'
  buttons: {
    primary: {
      textColor: string
      backgroundColor: string
    }
    secondary: {
      textColor: string
      backgroundColor: string
    }
    tertiary: {
      textColor: string
      backgroundColor: string
    }
  }
}

次に、ThemeをあなたのTS型で拡張して宣言します。これを同じ.tsxファイルで行うことができます(別の.tsファイルを作成する必要はありません)。

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