ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 리액트 네이티브 타입스크립트 네비게이션 에러
    개발 공부/혼자 하는 리액트 네이티브 2023. 4. 11. 13:39

    지금 진행 중인 리액트 네이티브 프로젝트를 시작할 때 너무 별 생각없이 타입스크립트로 바로 시작했다.

    자바스크립트는 많이 써봤으니 공부할 겸 해보자 였나, 아니면 샘플을 그대로 따라해서였나 기억은 잘 안나지만

     

    단점❗은 인터넷상에 샘플들은 거의다 JS 다. 코드를 그대로 긁어와도 꽤나 종종 에러가 뜬다. JS 문법에는 맞지만 TSX 문법에 맞지 않아서이데, 언뜻 보기에는 전체적으로 비슷하나 1-2개만 오류가 나서 처음엔 버전 문제인줄 알고 삽질을 많이 했다 ㅠㅠ (A TSX file is a TypeScript (.TS) file written using JSX syntax) 

     

    TS 기본기도 없었지만, 다들 TSX를 잘 안쓰는지 에러 관련 정보 자체도 찾기 힘들었다.

     

     

    오늘 기록할 에러는 Navigation 의 navigate function 에러이다. 

     

    페이지 이동 할 때 아래와 같이 구현하는데

    navigation.navigate('가고자하는페이지', {param}) 

    아무리 찾아봐도 다들 아래 소스로 잘만 사용하고 더 부가적인 코드도 필요 없는데 나는 아래와 같은 에러가 났다. 

    Argument of type 'string' is not assignable to parameter of type 'never'.

     

    에러의 원인은, JS와 달리 타입스크립트는 잘못된 타입을 사용하는 것을 방지하기 위해 내부적으로 장치가 있다. 그래서 아래와 같이 타입을 따로 정의해주어야 하는 경우가 많다.

     

    결국 navigation 에게 StackNavigationProp 으로 이동할 페이지에 대해 정의한 타입을 전달해주면 미리 타입을 갖고 있기 때문에 navigate function을 사용할 때 페이지를 string type으로 보내도 인식이 된다. 

    주의할 점은 RootStackParamList에 정의된 YourScreen 과 navigate 에 전달해주는 'YourScreen'이 같아야 한다. 

    import { StackNavigationProp } from '@react-navigation/stack';
    import { useNavigation } from '@react-navigation/core';
    
    export type RootStackParamList = {
      YourScreen: { id: number } | undefined;
    };
    
    const navigation = useNavigation<StackNavigationProp<RootStackParamList>>();
    
    <TouchableOpacity
       // Use this when you pass a parameter (is optional)
       onPress={() => navigation.navigate('YourScreen', {id: 5})}>
    </TouchableOpacity>

    Remember this notes:

    • Specifying undefined means that the route doesn't have params. A union type with undefined => AnyType | undefined means that params are optional.
    • The useNavigation const have special type and this final type takes 3 generics:
    • The param list object => RootStackParamList
    • The name of the screen route => RouteName
    • The ID of the navigator (optional) => NavigatorID

     

     

     

    위의 코드를 추가하자 아래와 같이 더이상 'ClassDetail'에 에러가 나지 않는 것을 볼 수 있다.

     

     

    반응형
Designed by Tistory.