Integrating Typescript into function parameters

I am attempting to make my function flexible by allowing it to accept either a string or a custom type

onPress: (value: string | CustomType)=>void

But when I try to assign a string or CustomType, the compiler gives an error saying

is not assignable to type '(value: string | CustomType ) => void'

Is there a solution to this issue?

Answer №1

It appears that there is a misunderstanding regarding the data type of your variable onPress. It is not simply a string | CustomType, but rather a function of type

(value: string | CustomType) => void
. This signifies a function that accepts a single argument of either type string or CustomType, and does not return any value.

You have the option to assign an existing function to the onPress variable:

type CustomType = number  // used for testing
let onPress: (value: string | CustomType) => void

function doSomething(value: string | CustomType) {
  console.log("Performing action with value " + value)
}

onPress = doSomething

onPress("BY432")

Alternatively, you can assign an anonymous function to it:

type CustomType = number  // used for testing
let onPress: (value: string | CustomType) => void

onPress = function (value) {
  console.log("Performing action with value " + value)
}

onPress("BY432")

Another option is to assign an arrow function (also anonymous):

type CustomType = number  // used for testing
let onPress: (value: string | CustomType) => void

onPress = value => console.log("Performing action with value " + value)

onPress("BY432")

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

The current value of React.createRef() is perpetually empty

Ever since I started working on this code, I've been encountering a problem that seems to have no solution. Here's what's going on: import React, { Component } from 'react'; export class InfoPaneArrow extends Component<InfoPane ...

Next.js routes handlers do not have defined methods parameters

Struggling to find the cause of undefined params Currently delving into the world of Nextjs api routes, I keep encountering an issue where my params are coming up as undefined when trying to use them in the HTTP method. My setup includes prisma as my ORM ...

The new mui v5 Dialog is having trouble accepting custom styled widths

I am facing an issue with my MUI v5 dialog where I cannot seem to set its width using the style() component. import { Dialog, DialogContent, DialogTitle, Paper, Typography, } from "@mui/material"; import { Close } from "@mui/icons- ...

angular-bootstrap-mdindex.ts is not included in the compilation result

Upon deciding to incorporate Angular-Bootstrap into my project, I embarked on a quest to find a tutorial that would guide me through the download, installation, and setup process on my trusty Visual Studio Code. After some searching, I stumbled upon this h ...

Jasmine was unsuccessful in detecting a exported function being invoked by another function

In my code, I've created 2 helper functions where one is a shortcut to the other. I need to verify in my test that the shortcut function is actually calling the main function. Both functions are located in the same file: export function test1(param1, ...

The ViewChild from NgbModalModule in @ng-bootstrap/ng-bootstrap for Angular 6 is causing the modal to return as

I have successfully integrated ng bootstrap into my project, specifically utilizing the modal module to display a contact form. The form includes input fields for email and message, as well as a submit button. You can find the ngbootstrap module I am using ...

Creating a non-editable form or text field upon clicking the Submit button

<form [formGroup]="calculateForm"> <div class="form-group row"> <p for="inputFrom" class="col-sm-4">Distance traveled ...

The Next.js app's API router has the ability to parse the incoming request body for post requests, however, it does not have the

In the process of developing an API using the next.js app router, I encountered an issue. Specifically, I was successful in parsing the data with const res = await request.json() when the HTTP request type was set to post. However, I am facing difficulties ...

"Exciting developments in Angular 17 with the introduction of the new @

I need to output elements from an array of strings starting at index 1. arr = [ "str1", "str2", "str3", "str4", "str5" ] The desired output is: str2 str3 str4 str5 To achieve this, use a new @for loop in ...

Whenever signing in with Next Auth, the response consistently exhibits the values of "ok" being false and "status" being 302, even

I am currently using Next Auth with credentials to handle sign-ins. Below is the React sign-in function, which can be found at this link. signIn('credentials', { redirect: false, email: email, password: password, ...

NodeJS Jest test failing due to a global variable being set for a different test already

I am currently working on a project in TypeScript using Node.js and Jest. I have a function that may or may not modify a global variable, which is a TypeScript Map. After one test modifies the global variable, it retains that value for subsequent tests. I ...

Using React to implement MUI autocomplete feature alongside a MUI form

Recently, I have been utilizing a MUI form structured in the following manner: <Box component="form" onSubmit={event => { return handleSubmit(event); }} noValidate sx={{mt: 1}}> <TextField margin="normal" ...

TypeScript does not verify keys within array objects

I am dealing with an issue where my TypeScript does not flag errors when I break an object in an array. The column object is being used for a Knex query. type Test = { id: string; startDate: string; percentDebitCard: number, } const column = { ...

How can you check the status of a user in a Guild using Discord JS?

Is there a way to retrieve the online status of any user in a guild where the bot is present? Although I can currently access the online status of the message author, I would like to be able to retrieve the online status of any user by using the following ...

Incorporating Precision to Decimal Numbers in TypeScript Angular

Having some trouble with this issue and I've tried various solutions without success. This problem is occurring within an Angular project. The requirement is to always display a percentage number with two decimal places, even if the user inputs a who ...

How can Mui typescript be extended with a unique wrapper that includes a `component` property?

I recently created a unique wrapper component: import Box, { BoxProps } from "@mui/material/Box"; type CustomWrapperProps = { id: string } & BoxProps const CustomWrapper = (props: CustomWrapperProps) => { const {id, children, ...rest ...

Fill out FormBuilder using data from a service within Angular2

I am working with an Angular2 model that I'm filling with data from a service. My goal is to use this model to update a form (created using FormBuilder) so that users can easily edit the information. Although my current approach works, I encounter er ...

Leveraging TweenMax within an Angular2 development venture

What is the best way to integrate TweenMax into my Angular2 project? I would like to avoid adding the script directly in my HTML and instead import TweenMax using the following syntax: import { TweenMax } from 'gsap'; Please keep in mind that I ...

Node.js has been giving me trouble as I try to install Inquirer

:***Hey Guys I'm Working on a TypeScript/JavaScript Calculator! ...

How can we optimize component loading in react-virtualized using asynchronous methods?

In my component, I have implemented a react-virtualized masonry grid like this: const MasonrySubmissionRender = (media: InputProps) => { function cellRenderer({ index, key, parent, style }: MasonryCellProps) { //const size = (media.submiss ...