[TS] Styled-Components에 TypeScript 적용하기

2022. 4. 10. 21:59·React/TypeScript

Styled-Components와 TypeScript를 함께 사용할 때 아래와 같은 에러가 발생한다.

Property 'isSelected' does not exist on type 
'Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, 
HTMLDivElement>, "key" | keyof HTMLAttributes<HTMLDivElement>> 
& { ...; } & ThemeProps<...>'

 

Styled-Components가 전달받은 프로퍼티에 타입이 지정되어 있지 않아 발생하는 에러이다.

크게 두 가지 해결법이 있다.

 

방법1

const SStyledBookmark = styled.div`
  color: ${({ isSelected, theme } : { isSelected : any, theme : any}) =>
...

단순하게 프로퍼티에 타입을 명시해주면 된다. 하지만 중복되는 프로퍼티가 많다면 방법2를 사용하는 것이 좋다.

 

방법2

interface Props {
  isSelected?: boolean;
  horizontal?: string;
  vertical?: string;
  width?: string;
  height?: string;
  justify_content?: string;
  align_items?: string;
  flex?: string;
  selected?: boolean;
  forPopup?: boolean;
  isOpened?: boolean;
  expand?: boolean;
}

const SStyledBookmark = styled.div<Props>`
  color: ${({ isSelected, theme }) =>

사용자 지정 프로퍼티들을 interface로 만들어 컴포넌트에 확장시키는 방법이다. Styled-Components에서 지원하는 최신 방법이다.

프로퍼티를 사용하고자 하는 컴포넌트에 위와 같이 확장시켜주면 된다.

저작자표시 비영리 변경금지 (새창열림)

'React > TypeScript' 카테고리의 다른 글

[TS] TypeScript Object 다루기  (0) 2022.04.10
[TS] React Typescript 변환하기  (0) 2022.04.09
'React/TypeScript' 카테고리의 다른 글
  • [TS] TypeScript Object 다루기
  • [TS] React Typescript 변환하기
박유상의 개발블로그
박유상의 개발블로그
개발블로그
  • 박유상의 개발블로그
    박유상의 개발블로그
    박유상의 개발블로그
  • 전체
    오늘
    어제
    • 전체 (134)
      • Who am I (10)
        • Portfolio (4)
        • Reminiscence (5)
        • Oversea (1)
        • SiliconValley (0)
      • React (36)
        • React Basic (15)
        • React Tech (5)
        • JavaScript (7)
        • TypeScript (3)
        • CSS&HTML (3)
        • Firebase (3)
      • NodeJS (1)
        • NodeJS Basic (1)
      • Flutter (55)
        • Flutter Widget Design (5)
        • Flutter Widget Basic (8)
        • Flutter Tech (18)
        • Flutter Issue (7)
        • Flutter Web (6)
        • About Flutter (2)
        • Firebase (1)
        • Dev Env (1)
        • Dart (7)
      • Programming (31)
        • Web (1)
        • General (0)
        • Algorithm (25)
        • Python (1)
        • VS Code (2)
      • Django (0)
  • 블로그 메뉴

    • Who I AM
    • React
    • NodeJS
    • Flutter
    • Programming
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    JSON
    리액트
    Firebase
    Flutter
    프로그래머스
    Python
    HTML
    react
    CSS
    DP
    DART
    map
    탐욕법
    useTranslation
    Redux
    useRef
    자바스크립트
    웹
    JavaScript
    포트폴리오
    플러터
    github
    알고리즘
    파이썬
    링고리
    flutter web
    TypeScript
    플러터 웹
    Lingory
    useState
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
박유상의 개발블로그
[TS] Styled-Components에 TypeScript 적용하기
상단으로

티스토리툴바