redux-toolkit에 타입스크립 적용하기: 타입 단언이 타입 캐스팅은 아니다

Maliethy·2021년 6월 2일
0

typescript

목록 보기
1/3

1. issue

redux-toolkit 공식문서를 보다 다음 구정에서 타입 단언과 타입 캐스팅이 어떤 차이가 있는지 궁금해졌다.

In some cases, TypeScript may unnecessarily tighten the type of the initial state. If that happens, you can work around it by casting the initial state using as, instead of declaring the type of the variable:

// Workaround: cast state instead of declaring variable type
const initialState = {
  value: 0,
} as CounterState

https://redux-toolkit.js.org/tutorials/typescript

2. solution

타입 단언은 타입을 변경한다는 사실 때문에 타입 캐스팅과 비슷하게 느껴질 수 있다. 타입 단언이 타입 캐스팅이라고 불리지 않는 이유는 런타임에 영향을 미치지 않기 때문이다. 타입 캐스팅은 컴파일타임과 런타임에서 모두 타입을 변경시키지만 타입 단언은 오직 컴파일타임에서만 타입을 변경시킨다.

출처: https://hyunseob.github.io/2017/12/12/typescript-type-inteference-and-type-assertion/

profile
바꿀 수 있는 것에 주목하자

0개의 댓글