*material-ui는 v5부터 typescript를 안정적으로 지원하기 때문에 @types/material-ui 같은 별도의 패키지는 필요 없음
*작성 이유
- Material-ui를 typescript로 적용하는 과정에서 theme, breakpoint, palette 등 type 선언에 대한 공식 문서의 설명이 친절하지 않다고 판단
*핵심
- node_modules/@material-ui/core/styles 디렉토리에서 기본 설정되어있는 타입 선언 및 구조를 뜯어보자
Issue
1) 활용 중인 material-ui 코드 중 공통 부분을 통합하고, typescript로 마이그레이션하는 과정에서 발생
2) style.ts에 theme을 생성하고 커스터마이징하는 과정에서 palette를 추가함
3) @material-ui/core/styles에 기본으로 설정되어있는 palette type 형식에 맞지 않아 error 출력됨
Solution
*배경 지식 : @material-ui는 theme을 생성하려면 createMuiTheme 함수가 필요하다.
1) 우리는 background 라는 컬러 코드의 타입을 (1)createMuiTheme과 (2)theme에 추가해줄 것이다.
- @material-ui/core/styles의 구조 상 두 가지의 타입 선언이 다르고, theme에 override할 때, theme으로 접근해야한다.
2) node_modules/@material-ui/core/styles 디렉토리에서 createMuiTheme.d.ts를 보면 찾고자하는 theme 관련 type을 확인할 수 있다.
3) createMuiTheme의 옵션 타입은 ThemeOptions를 받지만, 결과 값은 Theme type을 받는다.
4) ThemeOptions의 palette는 PaletteOptions이고, Theme의 palette는 Palette를 받는다.
즉, type PaletteOptions에서 background type을 입력해야하고, type Palette에서도 background type을 입력해야한다.
5) [그림1]의 createMuiTheme 내부에서는 palette.background가 할당되는 type이 PaletteColorOptions이고,
theme의 내부 palette.background는 PaletteColor 형식인 것을 확인할 수 있다.
6) 우리는 PaletteColorOptions 내부 background 타입과 PaletteColor내부 background 타입을 둘 다 바꿔줘야한다.
7) 이제 createMuiTheme.d.ts 에서 createPalette.d.ts 파일로 이동
"타입 선언하기"
8-1) 수정하고자 하는 타입, type PaletteColorOptions = SimplePaletteColorOptions | colorPartial이므로,
SimplePaletteColorOptions에 background?: string;을 추가한다.
(타입 수정은 styled.d.ts 파일에서 진행)
8-2) 수정하고자 하는 타입, type PaletteColor에 background?: string 을 추가한다.
(타입 수정은 styled.d.ts 파일에서 진행)
9) createMuiTheme 내 palette.primary.background
& theme.palette.primary.background의 타입이 string으로 선언됨
theme 또는 다른 추가 설정일 경우에도 같은 방법으로 interface 명칭을 체크한 후, 타입을 선언해주면 된다.
GitHub - mui-org/material-ui: Material-UI is a simple and customizable component library to build faster, beautiful, and more ac
Material-UI is a simple and customizable component library to build faster, beautiful, and more accessible React applications. Follow your own design system, or start with Material Design. - GitHub...
github.com
'Development > Front-End' 카테고리의 다른 글
반응형 웹(Responsive Web)의 이해 (1) | 2021.10.11 |
---|---|
웹 접근성(Web Accessibility)의 이해 (0) | 2021.10.10 |
import 구문 정리 sort-imports + ESlint rules (0) | 2021.07.12 |
[TIL] - [Javascript] 커링 Curring (& Partial application) (0) | 2021.05.18 |
협업 프로젝트에 필요한 Github 활용 방법 (0) | 2021.03.02 |