Adding types for useTheme from @react-navigation/native

398 Views Asked by At

I'm tyring to set types for useTheme() from @react-navigation/native. I have setted a theme type before for styled-components, but I can't find a way to set the theme type for react navigation theme.
theme.ts:

import { DarkTheme, DefaultTheme } from '@react-navigation/native';

export const theme = {
  light: {
    ...DefaultTheme,
    colors: {
      ...DefaultTheme.colors,
      primary: '#B0BEC5',
      secondary: '#29434E',
      error: '#D32F2F',
      text: '#212121',
      border: '#212121',
      activeTab: '#1976D2',
      inactiveTab: '#757575',
    },
  },
  dark: {
    ...DarkTheme,
    colors: {
      ...DarkTheme.colors,
      primary: '#212121',
      secondary: '#29434E',
      error: '#D32F2F',
      text: '#FFFFFF',
      border: '#FFFFFF',
      activeTab: '#4FC3F7',
      inactiveTab: '#FFFFFF',
    },
  },
};

my folder structure:

enter image description here

index.tsx:

export { shadow } from '@/theme/shadow';
export { spacing } from '@/theme/spacing';
export { theme } from '@/theme/theme';
export { typography } from '@/theme/typography';

What I attempted (styled.d.ts):

import '@react-navigation/native';
import theme from './theme';

declare module '@react-navigation/native' {
  type ThemeType = typeof theme;

  export interface DefaultTheme extends ThemeType {}
}

I am getting type error on my AppNavigator.tsx:

import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { useTheme } from '@react-navigation/native';
import React from 'react';
import { TabBarIcon } from '@/components';
import { HomeNavigator } from '@/navigation/HomeNavigator';
import { TABS } from '@/constants/navigation';

const Tab = createBottomTabNavigator();

export function AppNavigator() {
  const { colors } = useTheme();

  return (
    <Tab.Navigator
      screenOptions={({ route }) => ({
        headerShown: false,
        tabBarActiveTintColor: colors.activeTab,
        tabBarInactiveTintColor: colors.inactiveTab,

Error (same for inactive):

Property 'activeTab' does not exist on type '{ primary: string; background: string; card: string; text: string; border: string; notification: string; }'
1

There are 1 best solutions below

0
Nilton Schumacher F On

My solution was (styled.d.ts):

import '@react-navigation/native';
import { useColorScheme } from 'react-native';
import { theme } from '@/theme';

declare module '@react-navigation/native' {
  const scheme = useColorScheme();

  type ThemeType = typeof theme[scheme | 'light'];

  export interface Theme extends ThemeType {}
}