Vue3 type error - Type 'T' is not assignable to type 'UnwrapRef<T>'

shelly·2022년 7월 8일

문제상황

에러가 발생한 코드

에러 메시지

Type 'T' is not assignable to type 'UnwrapRef'.

해결방법

방법 1 : 타입 캐스팅

  • 하지만 이렇게 타입캐스팅을 setName함수의 파라미터가 변경되었을 때 보호할 수 없게된다. 😢
    타입캐스팅은 피할 수 있다면 피하는 것이 좋다고 배웠으니, 다른 방법도 찾아보자.

.

방법 2 : shallowRef

  • vue에서 제공하는 내장타입 shallowRef를 사용하면 오류가 사라진다.

.

  • 또한 방법 1에서 우려했던 파라미터 변경에도 보호받을 수 있기 때문에 shallowRef를 사용하는게 좋아보인다!

.

  • 그러나, vue3의 공식문서를 살펴보면, shallowRef는 deep한 변경은 감지를 하지 못한다고 한다. 그렇기 때문에 사용에 주의가 필요하다.

.

  • object 타입의 state가 필요하다면 shallowReactive를 사용하는 것도 좋다. 그러나 여전히 깊은 감지는 안되기 때문에 주의가 필요하다.

    const state = shallowReactive({
      foo: 1,
      nested: {
        bar: 2
      }
    })
    
    // mutating state's own properties is reactive
    state.foo++
    
    // ...but does not convert nested objects
    isReactive(state.nested) // false
    
    // NOT reactive
    state.nested.bar++

검색 키워드

  • Type 'T' is not assignable to type 'UnwrapRef'.
  • vue ref with generic

참고자료

0개의 댓글