Working with a function in the stylesheet of TypeScript in React Native allows for dynamic styling

When attempting to use variables in my StyleSheet file, I encounter a type error even though the UI works fine. Any suggestions on how to resolve this issue?

type buttonStyle = (height: number, width: string, color: string) => ViewStyle;

export type Styles = {
  button: buttonStyle;
};

export default StyleSheet.create<Styles>({
  button: (height: number, width: string, color: string) => ({
    height: height,
    width: width,
    backgroundColor: color,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 10,
  }),
});

The error message related to types is as follows:

Type 'Styles' does not satisfy the constraint 'NamedStyles<any> | NamedStyles<Styles>'.
  Type 'Styles' is not assignable to type 'NamedStyles<Styles>'.
    Types of property 'button' are incompatible.
      Type 'buttonStyle' is not assignable to type 'ViewStyle | TextStyle | ImageStyle

Answer №1

To define a constant style, you can use the StyleSheet.create() method outside of your component:

const customStyles = ((height: number, width: string, color: string)) => StyleSheet.create({
    btn: {
        height: height,
        width: width,
        backgroundColor: color,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 10,
    }
});

Then, you can apply this style in your component like so:

<Button style={customStyles(height, width, color).btn} />

Answer №2

const styles = StyleSheet.create<CustomStyles | any>({
  customButton: (height: number, width: string, color: string) => ({
    height: height,
    width: width,
    backgroundColor: color,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 10,
  }),
});

Remember to include the any type, just like in this example.

StyleSheet.create<CustomStyles | any>

Answer №3

It appears that StyleSheet does not include a function type, so I have resolved this issue using the following method.

CSS file

import type { ViewStyle } from 'react-native';

const styles = {
  button: (height: number, width: string, color: string): ViewStyle => ({
    height: height,
    width: width,
    backgroundColor: color,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 10,
  }),
};

export default styles;

There is no requirement to specify the styles type explicitly.

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

Type of event triggered by user file upload via INPUT element

I have a piece of code that reads the contents of a locally stored file. Here is what it looks like: onFile(event: any) { console.log(event); const file = event.target.files[0]; const reader = new FileReader(); reader.onloadend = (ev: any) => { ...

Discovering the JavaScript source file for a package using WebStorm and TypeScript

In my TypeScript project, there is a usage of Express with the following method: response.send('Hello'); I am interested in exploring the implementation of the send() method. However, when I try to navigate to the source code by ctrl+clicking o ...

What is the necessity behind keeping makeStyles and createStyles separate in Material UI with TypeScript?

Dealing with TypeScript issues in Material UI has been a frequent task for me, and I find it frustrating that styling components requires combining two different functions to create a hook every time. While I could use a snippet to simplify the process, it ...

Eslint highlighting the initial function declaration within a Vue script

I'm currently creating a Vue file using a Typescript script, and encountering an unusual Eslint "error." The issue arises on line 15 with this specific complaint: Parsing error: Unexpected token, expected "," Interestingly, this error only occurs wi ...

The specified type 'ListRenderItem<IPhotos>' cannot be assigned to type 'ListRenderItem<unknown>'

Can someone assist with resolving this error I'm encountering: Type 'ListRenderItem<IPhotos>' is not assignable to type 'ListRenderItem<unknown> Here is the code snippet: import { Dimensions, Image, ListRenderItem, Pressabl ...

What could be causing a blank page to appear after being redirected? (Using NextJS 13 API Route)

After struggling with this issue for 2 days, I'm throwing in the towel and reaching out to the community for assistance. I've been tasked with setting up a basic login system for a new project using NextJS v13. However, it seems like a lot has c ...

Asynchronous retrieval of reference value from Firebase Firestore in ReactJS

Encountering a peculiar bug in TypeScript-JavaScript where I have a Model class in TypeScript and a ReactJS Component in JS. The issue arises when dealing with a list of Promo Objects, each containing a "_listCompte" property which holds a list of Compte O ...

Retrieving values from an array in a JSON response using Angular 4

How can I access the SubjectCode field in an array at a table using Angular 4? When trying to do so, I receive the error message: "[Error trying to diff '[object Object]'. Only arrays and iterables are allowed]". Here is the Json Response: { ...

Dealing with errors within nested requests while using switchMap with RxJS

I am faced with a situation where I need to make 2 dependent API calls: the getCars call requires the user id obtained from getUser. There is a possibility that a user may not have any cars, resulting in a 404 error from the API. How can I handle this sc ...

Experiencing unexpected output from Angular model class method

I have developed a user-friendly Invoicing & Inventory management application that showcases a list of invoices for each customer. However, there seems to be an issue with the calculation of the Grand Total function, which I am struggling to rectify due to ...

Having trouble with Typescript module path resolution for .js files?

I have embarked on a project in React and I am eager to begin transitioning the js files to typescript. The setup for aliases seems to function smoothly when importing .tsx within another .tsx file, however, it encounters issues when attempting to import . ...

The type 'number' cannot be assigned to the type 'Element'

Currently, I am developing a custom hook called useArray in React with TypeScript. This hook handles array methods such as push, update, remove, etc. It works perfectly fine in JavaScript, but encounters errors in TypeScript. Below is the snippet of code f ...

Material UI's dark mode primary button disappears on the appbar

I've been experimenting with implementing material-ui's dark mode in a React app. After going through the documentation, I was able to activate it successfully. However, I encountered an issue: when using a basic AppBar with a primary button on i ...

(NextAuth) Error: The property 'session' is not found within the existing type '{}'

While working on a NextJs project with NextAuth, I encountered the following error: "Type error: Property 'session' does not exist on type '{}'.". To resolve this issue, I added the session property to my _app.tsx file as sugg ...

Typescript error: RequestInit not properly initialized

I'm encountering an issue while using fetch to call an API in a typescript file. The browser is throwing an error stating that const configInit must be initialized, even though I believe it is already. Any suggestions on how to resolve this? Thank you ...

Encountering difficulties in creating a custom Response type in Express.js with TypeScript

I have encountered a TypeScript error while trying to create my own custom Response interface by extending some methods instead of using the default Response type of Express.js: The last overload resulted in the following error: Argument of type '(r ...

Update of Angular Material Table rows triggers a popup, however only the values from the first array are populated in all edited rows

Developed an application with two components (A & B) that includes a popup dialog for editing: Component A fetches the data from a service and loads it into a data table Component B initializes the data when a pop event is triggered from A. Usually, ...

Can someone share with me the best practices for implementing @HostListener within a method in my Angular 16 project?

Currently, I've been involved in developing a Single Page Application using Angular 16, TypeScript, and The Movie Database (TMDB). My task at hand is to implement the "infinite scroll" functionality on a particular component. To achieve this, I have ...

Tips for creating a test to choose a movie from the MuiAutocomplete-root interface

I am currently utilizing Material UI with React using Typescript and I am looking to create a test for the autocomplete functionality using Cypress. Here is the approach I have taken: Identifying the Autocomplete component and opening it, Choosing an opti ...

Adjusting the value of a mat-option depending on a condition in *ngIf

When working with my mat-option, I have two different sets of values to choose from: tempTime: TempOptions[] = [ { value: 100, viewValue: '100 points' }, { value: 200, viewValue: '200 points' } ]; tempTimesHighNumber: TempOpt ...