inflearn logo
강의

Course

Instructor

Learning React.js with TypeScript: From Basics to the Latest Technologies Perfectly

styled-components (Global)

styled-components(전역)

26

dbstjdgur08986

1 asked

0

 

// main.tsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import { ThemeProvider } from "styled-components";

const theme = {
  colors: {
    primary: "red",
    secondary: "#gray",
  },
  fontSizes: {
    normal: "16px",
    large: "20px",
  },
};
createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <ThemeProvider theme={theme}>
      <App />
    </ThemeProvider>
  </StrictMode>,
);

// App.tsx
import styled, { keyframes, css } from "styled-components";

const boxShadowMixin = css`
  margin: 20px;
  box-shadow: 0px 10px 10px rgba(0, 0, 0, 0.5);
`;

const fadeIn = keyframes`
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
`;

const Title = styled.h1<{ $color: string; $decoration: string }>`
  color: ${(props) => props.$color};
  text-decoration: ${(props) => props.$decoration};
  animation: ${fadeIn} 2s ease-in;
`;

const BigTitle = styled(Title)`
  font-size: 50px;
`;

const Wrapper = styled.section`
  padding: 2rem;
  border: 1px solid red;
`;

const BlueBorderWrapper = styled(Wrapper)<{ $shadow: boolean }>`
  border-color: ${(props) => props.theme.colors.primary};
  ${(props) => props.$shadow && boxShadowMixin};
`;

export default function App() {
  return (
    <>
      <BlueBorderWrapper $shadow={true}>
        <Title $color="#00ff00" $decoration="line-through" as="p">
          App Component
        </Title>
        <BigTitle $color="#0000ff" $decoration="underline">
          App Component
        </BigTitle>
      </BlueBorderWrapper>
    </>
  );
}
border-color: ${(props) => props.theme.colors.primary};

적용하는 부분에서 에러가 발생합니다.

Property 'colors' does not exist on type 'DefaultTheme'.

혹시 문제가 있는걸까요?

react react-router redux-toolkit zustand react.js

Answer 1

0

sucoding

안녕하세요.

styled-componentsDefaultTheme은 기본적으로 빈 인터페이스({})로 정의되어 있어서, 커스텀 theme 객체의 타입을 자동으로 인식하지 못합니다.

따라서 props.theme.colors에 접근하려 하면 TypeScript가 해당 프로퍼티가 없다고 에러를 냅니다.

해결 방법

DefaultTheme모듈 선언(Declaration Merging) 으로 확장해야 합니다.

1. styled.d.ts 파일 생성

// src/styled.d.ts
import "styled-components";

declare module "styled-components" {
  export interface DefaultTheme {
    colors: {
      primary: string;
      secondary: string;
    };
    fontSizes: {
      normal: string;
      large: string;
    };
  }
}

2. (선택) theme 객체에 타입 명시

main.tsx에서 theme 객체가 DefaultTheme을 만족하는지 컴파일 타임에 검증하고 싶다면 타입을 직접 지정할 수도 있습니다.

// main.tsx
import { DefaultTheme } from "styled-components";

const theme: DefaultTheme = {
  colors: {
    primary: "red",
    secondary: "gray", // ← "#gray"도 오타이니 이 기회에 수정
  },
  fontSizes: {
    normal: "16px",
    large: "20px",
  },
};

styled.d.ts 파일 하나만 추가하면 프로젝트 전체에서 props.theme.colors, props.theme.fontSizes 타입 추론이 정상적으로 동작합니다.

cloudinary 관련

0

48

3

useOptimistic 실전-1 useState

0

71

2

discord 초대장 갱신이 필요한거같습니다.

0

65

1

할일 관리 앱(메모이제이션)

0

82

2

Web 플랫폼 등록

0

111

2

함수 정의 기준

0

80

2

fetch는 사용되는가

0

78

2

전역상태 관리 선택 기준

0

91

2

tailwind css는 언제 사용되는가 또 다른 css와의 차이

0

162

2

카카오 web플랫폼 등록

0

159

2

컴포넌트 그리고 폴더 구조에 대해

0

63

2

152강 보는중입니다. 초시계부분이구요. 넘버가 timeout을 받을수없다는 에러가 나오고 있어요

0

45

1

폼테그 다른 태그를 하나의 상태 객체로 묶기

0

47

2

class를 className으로 전부 수정하실 때

0

46

2

JWT에 대한 개념도 학습할 수 있나요?

0

68

2

수업자료 다운로드

0

56

2

리액트 객체의 타입을 알기위하여 마우스를 올렸을 때 나오는 형식이 강의와 다른 부분 문의 드립니다.

0

68

2

useState 자동생성 하실때 누른 키보드가 궁금합니다.

0

55

1

타입스크립트 타입이 불일치하는데 에러가 안납니다.

0

78

3

default format >> prettier 이 실행이 안됩니다.

0

69

2

윈도우 사용자입니다. homebrew 윈도우 설치법은 없나요?

0

353

3

리렌더링 관련 문의

0

60

2

공부 방향에 대해서

0

67

2

form action 과 onSubmit

0

65

2