React Native Typescript: Issue with non-existent property

After dabbling in TypeScript for React Native, I've encountered some rather strange error messages that have me stumped.

While experimenting with my code, I came across this line:

<Text text={user?.last_name} style={{color:colors.textSecondary}} variant="labelMedium"/>

Visual Studio Code is flagging an issue with colors.textSecondary:

Property 'textSecondary' does not exist on type '{ primary: string; background: string; card: string; text: string; border: string; notification: string; }'.ts(2339)

Surprisingly, using colors.text works just fine, and I'm puzzled as to why. Here's the snippet from the theme file where I'm defining the standard theme colors:

export const Theme = {
light: {
    mode: 'light',
    colors: {
      primary: '#1976d2',
      secondary: '#7393B3',
      background: '#f9f9f9',
      card: '#ffffff',
      text: '#303233',
      textSecondary: '#727272',
      border: '#e8e8e8',
      error: '#f44336',
    },
  },
  dark: {
    mode: 'dark',
    colors: {
      primary: '#1976d2',
      secondary: '#7393B3',
      background: '#171819',
      card: '#202122',
      text: '#e4e6eb',
      textSecondary: '#b0b3b8',
      border: '#333435',
      error: '#f44336',
    },
  },
};

Where could I be going wrong here? Strangely enough, the text color displays correctly despite the error.

Thanks! Jan

Answer №1

An issue arises due to the structured properties of React Native's Theme. The predefined properties can be found in:

The additional theme property you introduced is not recognized by TypeScript, as it extends beyond the known properties. By adding an extra property to your theme, the consuming code remains unaware of its existence since it only recognizes the base Theme properties defined by React.

Upon reviewing the library, there doesn't seem to be a straightforward method for expanding the available properties of the Theme type (though some suggestions have been made in comments). Here are a few recommended options:

  1. Bypass TypeScript by using bracket notation. Using bracket notation may lead TypeScript to overlook checking the property. It might vary based on the situation, but it's worth exploring.
style={{color:colors['textSecondary']}}
  1. Create a custom theme that encompasses both the known props and the core theme props with strong typing.
import {Theme, useTheme} from "@react-navigation/native";

type CustomTheme = Theme & {
    colors: {
        textSecondary: string;
    };
};

export function useCustomTheme(): CustomTheme {
    return useTheme() as any;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngluarFire 2 authState function displaying null after refreshing the page

Currently, I am working on integrating Firebase with AngularFire 2 and facing an issue. The problem arises when I try to refresh the page, as the auth instance returns null. Below is the code snippet for my AuthService: Everything functions correctly, b ...

Tips on refreshing a view in react as data updates

Currently, I am delving into learning a variety of subjects such as Typescript, Express, and my newfound interests in REACT and RXJS. To aid in my studies, I created a Quick-List on Github, but encountered a question... "How can the view in React be upda ...

How can a variable be used to assign a date value to an Angular Material datepicker?

Is there a way to modify the date of an item in an array? I've encountered an issue when attempting to input the selected object's date into the Material datepicker. Strangely, it seems to function properly if you manually type in a date as a str ...

React/TypeScript - react-grid-layout: The onDrag event is fired upon clicking the <div> element

I am currently working on creating a grid with clickable and draggable items using the react-layout-grid component. However, I am facing an issue where the drag is instantly activated when I click on the item without actually moving the cursor. Is there a ...

The value 'var(--header-position)' cannot be assigned to type 'Position or undefined'

Description of Issue I am attempting to utilize a CSS Custom Property to customize a component within a nextjs application using TypeScript. Strangely, all CSS properties accept the CSS variables except for the position property which triggers the error b ...

The values obtained from an HTTP GET request can vary between using Curl and Ionic2/Angular2

When I make a GET request using curl in the following manner: curl https://api.backand.com:443/1/objects/todos?AnonymousToken=my-token I receive the correct data as shown below: {"totalRows":2,"data":[{"__metadata":{"id& ...

TypeScript is unable to recognize files with the extension *.vue

Can someone assist me with an issue I'm facing in Vue where it's not detecting my Single File Components? Error message: ERROR in ./src/App.vue (./node_modules/ts-loader!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/Ap ...

Step-by-step guide on adding a command to a submenu through the vscode extension api

I'm developing a Visual Studio Code extension and I want to include a command in a submenu like this https://i.stack.imgur.com/VOikx.png In this scenario, the "Peek" submenu contains commands such as "Peek Call Hierarchy". My current Package.json fi ...

Guide on importing and using types from an external library in my declaration file

Querying Library Types in a .d.ts Declaration File I am currently working on creating a custom namespace in a cf.d.ts file to define general-purpose types for my application. This allows me to avoid importing modules repeatedly whenever I need to referenc ...

Error: Module '/node_modules/.vite/deps/react-pro-sidebar.js?v=913080ef' does not export 'ProSidebar' as requested

Using the pro-side-bar library in React is causing an issue for me. When I run the code, the console shows the following error using the dev tools: Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/react-pro-sidebar.js?v=913080ef& ...

What is the correct way to utilize the createAsyncThunk function in TypeScript?

You can access the entire project here. I currently have this code snippet: extraReducers: (builder) => { builder .addCase(getTodosAsync.fulfilled, (state, action:any) => { return action.payload.todos ...

Managing singleton instances in TypeScript and NextJs across multiple files

Lately, I've been immersed in a personal project that involves creating API endpoints using NextJs and TypeScript to interact with the Discord API via discord.js. Don't worry if you're unfamiliar with the discord API, as the focus here is no ...

Suggestions for Implementing a Smooth Login Experience in React Native

As a newcomer to the world of react-native, I am facing a challenge in creating a login feature that interacts with our backend APIs on AWS. The goal is to navigate to the home screen upon receiving a token from the API, while displaying an error message i ...

Extracting data from response body in Angular after encountering 403 error during HTTP Post request

I am currently working on an Angular 9 project where I handle login functionality using HTTP post and HttpClient. In case of a failed login attempt, the server responds with HTTP status code 403 and a JSON object containing the error message that needs to ...

MUI Autocomplete refuses to accept a value

In my Autocomplete feature, I have a list of all users available. When a user clicks on a button from another site, they are redirected to this site and the user's ID is fetched. I want the user with the corresponding ID to be automatically selected, ...

Updating the view of an HTML page in Angular after a set period of time can be achieved by

I am facing an issue while trying to dynamically display a router link based on a certain condition. The goal is to show the routerLink name within the div section if a specific condition is met. Initially, when I check {{isNameAvailable}}, it returns fals ...

Is it possible for the app-routing.module.ts to have two paths with :/id?

When attempting to access the maindetail and childdetails pages using :/id, I encountered an issue on localhost where the desired card was not displaying on the maindetail page. The goal is to be able to click on the name "aniq" in the dashboard (image 1) ...

NGXS no longer functions properly when upgrading to Angular 9 and enabling Ivy

I am currently in the process of upgrading my Angular application to version 9. I have encountered an issue where everything runs smoothly when Ivy is disabled, but enabling Ivy causes the application's serve task to not finish correctly: Here is a s ...

Error in Angular: Trying to access the property 'id' of an undefined value

I am facing an issue with a div tag in my HTML file. The code snippet looks like this: <div *ngIf="chat.asReceiver.id != user?.id; else otherParty"> Unfortunately, it always returns the following error: ERROR TypeError: Cannot read propert ...

Expanding the typings for an established component in DefinitelyTyped

Is there a way to define new typings for additional props in DefinitelyTyped? After updating the material-ui library with some new props for the SelectField component, I realized that the typings in DefinitelyTyped are outdated. Is it possible to extend th ...