TIL: RN, TS | ReactNavigation Type checking (1) - 220910

Lumpen·2022년 9월 11일
0

ReactNavigation

목록 보기
1/14

RactNavigation

react navigation은 typescript로 작성되었기 때문에
typescript에 대한 유형 정의를 가지고 있다

내비게이터를 확인하는 유형

route 이름과 매개변수의 유형을 확인하려면
route의 매개변수에 대해 이름 매핑이 있는 객체 유형을 생성해야 한다

ex) userId를 param으로 갖는 Profile 루트 내비게이터

type RootStackParamList = {
  Profile: { useId: string } 
}

각 경로에 대해 동일한 작업을 수행해야 한다

type RootStackParamList = {
  Home: undefined
  Profile: { userId: string }
  Feed: { sort: 'latest' | 'top } | undefined
}

타입 유형이 undefined일 경우가 있다는 것은
선택적으로 params를 넘겨줄 수 있다는 것이다

import { createStackNavigator } from '@react-navigation/stack

const RootStack = createStackNavigatore<RootStackParamList>()
<RootStack.Navigator initialRouteName="Home">
  <RootStack.Screen name="Home" component={Home} />
  <RootStack.Screen
    name="Profile"
    component={Profile}
    initialParams={{ userId: user.id }}
  />
  <RootStack.Screen name="Feed" component={Feed} />
</RootStack.Navigator>

Navigator 와 Screen Components Props에 대한 타입 유형 검사 및
intellisense를 제공한다

IntelliSense는 코딩을 편리하게 하는 기능으로 여기에서는 자동완성 등을 말하는 듯..

screens 타입 체크

react-navigation에서 navigator 패키지는
해당 navigator로 부터 네비게이션과 route props 모두 정의하는 제네릭 타입을 내보낸다

ex) NativeStackScreenProps를 NativeStack Navigator에 사용할 수 있다

import type { NativeStackScreenProps } from '@react-navigation/native-stack';

type RootStackParamList = {
  Home: undefined;
  Profile: { userId: string };
  Feed: { sort: 'latest' | 'top' } | undefined;
};

type Props = NativeStackScreenProps<RootStackParamList, 'Profile'>;

타입이 갖는 3가지 제네릭

  • 정의한 매개 변수 list object
  • 화면이 속한 route의 이름
  • navigator의 ID (optional)

navigator가 ID를 갖는다면 다음과 같이 할 수 있다

type Props = NativeStackScreenProps<RootStackParamList, 'Profile', 'MyStack'>;

이를 통해 navigate, push 등을 사용중인 route의 이름 및 params의 타입을 확인할 수 있다
route.params에서 params를 입력하고 setParams를 호출할 때 params를 입력하려면 현재 경로의 이름이 필요

https://reactnavigation.org/docs/typescript/#type-checking-screens

profile
떠돌이 생활을 하는. 실업자는 아니지만, 부랑 생활을 하는

0개의 댓글