Development/Front-End

Material-ui (with Typescript) type 수정하기

highcastlee 2021. 8. 19. 23:16

 

*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 출력됨

 

 

[그림1] palette.primary에 background color를 임의로 추가했을 때, 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을 입력해야한다.

 

[그림2] palette?: PaletteOptions와 palette: Palette에 background:string을 추가할 것이다.

 

5) [그림1]의 createMuiTheme 내부에서는 palette.background가 할당되는 type이 PaletteColorOptions이고,

   theme의 내부 palette.background는 PaletteColor 형식인 것을 확인할 수 있다.

 

[그림3] 같은 background 컬러 코드이지만, 할당되는 type이 다른 것을 알 수 있음

 

6) 우리는 PaletteColorOptions 내부 background 타입과 PaletteColor내부 background 타입을 둘 다 바꿔줘야한다.

 

7) 이제 createMuiTheme.d.ts 에서 createPalette.d.ts 파일로 이동

 

[그림4] PaletteOptions 내 PaletteColorOptions, PaletteType 등 여러 type 객체가 속해있다.

 

[그림5] interface Palette는 createPalette 결과 값의 타입이다.

 

"타입 선언하기"

 

8-1) 수정하고자 하는 타입, type PaletteColorOptions =  SimplePaletteColorOptions | colorPartial이므로,

   SimplePaletteColorOptions에 background?: string;을 추가한다.

   (타입 수정은 styled.d.ts 파일에서 진행)

 

8-2) 수정하고자 하는 타입, type PaletteColor에 background?: string 을 추가한다.

   (타입 수정은 styled.d.ts 파일에서 진행)

 

[그림6] 프로젝트 type 선언을 위한 styled.d.ts 파일 내부에서 원하는 Palette 타입을 선언해준다.

 

 9) createMuiTheme 내 palette.primary.background

    & theme.palette.primary.background의 타입이 string으로 선언됨

 

theme 또는 다른 추가 설정일 경우에도 같은 방법으로 interface 명칭을 체크한 후, 타입을 선언해주면 된다.

 

 

 

 

 

 

[Material-ui github]

 

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