How do I create a generic function in TypeScript that adjusts its behavior based on the input argument?

Is there a way to create a generic function that can accept generic arguments like Data<string, number>?

Take a look at this code snippet:

interface Data<T,R> {
    a:T;
    c:R;
}

function foo(
  data: Data<string, number>
){
 return test(data)
}

//trying to make this function generic
function test<?, T extends Data<?, ?>>(
  data: T,
): T {
  return data
}

Any suggestions on how to approach this?

Answer №1

Here is the code snippet:

interface Data<T,R> {
    a: T;
    c: R;
}

function foo(
  data: Data<string, number>
){
 return test(data)
}

//this function should be made generic
function test<T,R>(
  data: Data<T,R>,
): Data<T,R> {
  return data
}

Link to TypeScript Playground

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

Discover how TypeScript's strictNullChecks feature can help you identify null values with ease in your functions

Since Javascript often requires me to check if a value is `!= null && != ''`, I decided to create a function that checks for empty values: const isEmpty = (variable: any, allowEmptyString?: boolean): boolean => { return variable == null | ...

The element 'commit' cannot be found within the property

I am facing an issue when transitioning from using Vuex in JavaScript to TypeScript. The error message Property 'commit' does not exist appears in Vuex's mutations: const mutations = { methodA (): none { this.commit('methodB' ...

Tips on programmatically filtering angular lists

Is there a way to programmatically filter an Angular list? I'm currently working on a project where I need to filter subcategories by clicking on categories. For example, when clicking on "Drinks," I want to display items like Coke, Fanta, Pepsi... ...

Angular is having trouble locating the module for my custom library

Trying to implement SSR in my angular application, but encountering an error when running npm run build:ssr. I've created my own library named @asfc/shared, which is bundled in the dist folder. ERROR in projects/asfc-web/src/environments/environment. ...

What is causing the ESLint error when trying to use an async function that returns a Promise?

In my Next.js application, I have defined an async function with Promise return and used it as an event handler for an HTML anchor element. However, when I try to run my code, ESLint throws the following error: "Promise-returning function provided t ...

Tips for resolving the 'JSX is not defined no-undef' error post TypeScript 4.4.2 update

Upon upgrading to TypeScript 4.4.2 from TypeScript 3.8.2, I have encountered numerous errors such as error 'x' is not defined no-undef. For instance, one of the errors is error 'JSX' is not defined no-undef. Upon closer inspection, most ...

Encountered a problem when implementing flowbite in a project using NextJS and TypeScript

I recently added tailwind and flowbite to my NextJS project. After importing "flowbite" in the _app.tsx file, I encountered the following error message: ReferenceError: document is not defined at Object.366 (D:\shopflo\next-tailwin ...

React: State updates are not reflecting in the UI components

I am facing an issue where a function component is not updating visually when the state changes. To illustrate this problem, I have included a simple example of my component in which I update the state but the component does not reflect these changes in t ...

The type 'string' cannot be assigned to the type 'T[keyof T]' within this context

I have a function that processes an array of Episodes and assigns data from an external file to the corresponding Episode based on a specified keyName: const assignDataFromExternalFile = (arrayToProcess: Episode[], filePath: string, keyName: keyof Episode) ...

Mixing TypeScript generic types loosely

Let's explore a simple example of typescript mixins: import { Observable, of } from 'rxjs'; class Service<TDataType> { public foo(f: TDataType): Observable<TDataType> { return of(f); } } type GConstructor<T = {}> = new ...

TypeScript - Issue with generic function's return type

There exists a feature in typescript known as ReturnType<TFunction> that enables one to deduce the return type of a specific function, like this function arrayOf(item: string): string[] { return [item] } Nevertheless, I am encountering difficulti ...

Utilize generic types as object properties in TypeScript

Is there a way to achieve something similar in TypeScript like the following: export type CoordinateSelector = <T>(d: Coordinate) => d[T]; export interface LinkVerticalLineProps { x: CoordinateSelector<'x'>; y: CoordinateSele ...

Angular HighCharts - Retrieving chart data via API

My goal is to populate the data property of my chart with values obtained from an external API: . I've defined an Interface that matches the structure of the data: export interface ChartData{ item1: number; item2: number; ...

looking to restrict the interface to only specific types

Currently working with TypeScript and I have a query regarding the utilization of TypeScript interface. Is there a way to selectively extract and output specific key types from the interface being used? While I am able to isolate the type I need, I am inte ...

Ensuring Consistency in Array Lengths of Two Props in a Functional Component using TypeScript

Is there a way to ensure that two separate arrays passed as props to a functional component in React have the same length using TypeScript, triggering an error if they do not match? For instance, when utilizing this component within other components, it sh ...

Using Typescript and react-redux with a Stateful Component: The parameter type 'typeof MyClass' does not match the expected component type

I've been trying to dive into the world of Typescript, React, and Redux. However, I've hit a roadblock at the moment. This is the error I encountered: ./src/containers/Hello.tsx [tsl] ERROR in /home/marc/Development/TypeScript-React-Starte ...

On MacOS, VSCode encounters an issue with updating TypeScript imports when files are moved

I recently started transitioning a project from a mixed JS/TS setup to fully TypeScript. The project's server is hosted on AWS Lambda, and I have a tsconfig file at the root level as well as one in the /lambdas directory. One issue I've encounte ...

Error in TypeScript React: 'Display' property is not compatible with index signature

My design page in React with TypeScript template is using Material UI, with custom styles implemented using the sx prop of Material UI. To customize the styling, I have created a separate object for the properties related to the sx props: const myStyles = ...

What is the best way to move between components within the same parent class using UI router in Angular 6?

Explore the Angular UI-Router Visualizer design.component.ts import { Component, OnInit, ChangeDetectorRef, EventEmitter, Output, Input } from '@angular/core'; import { AppService } from '@app/shared/app.service'; import { Schema } fr ...

Ways to apply the strategy pattern in Vue component implementation

Here's the scenario: I possess a Cat, Dog, and Horse, all of which abide by the Animal interface. Compact components exist for each one - DogComponent, CatComponent, and HorseComponent. Query: How can I develop an AnimalComponent that is capable of ...