LoginSignup
6
1

More than 3 years have passed since last update.

TypeScript + styled-components で Theme に型をつける

Posted at

概要

styled-components では <ThemeProvider> を用いることで、プロジェクト全体で使用するカラーコードの Theme を取り扱うことができます。
https://www.styled-components.com/docs/advanced#theming
この記事ではこの Theme に対して独自の型を定義する方法を紹介します。

環境

  • react@16.9.0
  • typescript@3.5.3
  • styled-components@4.3.2
  • @types/styled-components@4.1.18

リポジトリ

方法

styled-components モジュール内部の DefaultTheme という interface に対して型をつけることで目的を達成できます。
この方法は @types/styled-components のコメントで言及されているやり方です。
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/5ce56f22065bc465282b94b0537743d342be3fa7/types/styled-components/index.d.ts#L407-L414

src/types/styled-components.d.ts

次のような感じで .d.ts ファイル内で styled-components の型定義を拡張してやります。

export interface Theme {
  black: string,
  white: string,
}

declare module "styled-components" {
  interface DefaultTheme extends Theme {}
}

src/Hello.tsx

使用する側はこのような感じです。コメントにある通り、 theme.black のところで型の補完が効きます。

import * as React from "react";
import { ThemeContext } from 'styled-components';

const Hello: React.FC = () => {
  const theme = React.useContext(ThemeContext);
  theme.black // <= 補完が効く
  return <div>Hello!</div>
}

export default Hello;
6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1