react-nativereact-navigationreact-native-navigation

How to fix the Type Error ,,TransitionSpec throw type error in React Native Custom Animation of StackNavigator from @react-navigation/Stack


As i am implementing the Custom animation while user navigate through screen i got a type error. in the Stack Navigator section while using available property for custom animation i.e transitionSpec


import { Easing, StyleSheet, Text, View } from "react-native";

import Home from "./screens/Home";
import Details from "./screens/Details";

import {
  createStackNavigator,
  CardStyleInterpolators,
} from "@react-navigation/stack";
import { NavigationContainer } from "@react-navigation/native";
export type RootStackParamList = {
  Home: undefined; // No parameters expected for Home screen
  Details: undefined;
};

const Config = {
  animation: "spring",
  config: {
    stiffness: 1000,
    damping: 50,
    mass: 3,
    overshootClamping: false,
    restDisplacementThreshold: 0.01,
    restSpeedThreshold: 0.01,
  },
};
const closeConfig = {
  animation: "timing",
  config: {
    duration: 200,
    easing: Easing.linear,
  },
};

const Stack = createStackNavigator<RootStackParamList>();
export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator
        screenOptions={{
          gestureDirection: "horizontal",
          transitionSpec: {
            open: Config,
            close: closeConfig,
          },
          cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
        }}
      >
        <Stack.Screen name="Home" component={Home} />
        <Stack.Screen name="Details" component={Details} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
});

The type error i got is in the transitionSpec on open and close property. below is the error i have post [![while i was implementing custom animation for screen transition and i was using React-Navigation/native i got the following error however there is not error in the app while running on emulator?


Solution

  • It's because timing and spring are inferred as string instead of the literal value. You can try adding as const:

    const closeConfig = {
      animation: "timing",
      config: {
        duration: 200,
        easing: Easing.linear,
      },
    } as const
    

    Or

    const closeConfig = {
      animation: "timing" as const,
      config: {
        duration: 200,
        easing: Easing.linear,
      },
    }
    

    Alternatively annotate the constant with the type:

    const closeConfig: TransitionSpec = {
      animation: "timing",
      config: {
        duration: 200,
        easing: Easing.linear,
      },
    }