A series of functions with designated return types passed to the subsequent function

I have a vision to craft an innovative array that is filled with functions.

const a = [
  (): { a: string } => ({ a: 'alpha'}),
  ({ a }): { b: string } => ({ b: 'beta' }),
  ({ a, b }): {} => ({}),
]

The functions are specified with return types, but I desire a method to eliminate the need for specifying input types and instead generate a "chaining" mechanism where all inputs are merged into the return types of previous functions in the sequence.

If achieving this directly isn't feasible, could I at least implement an interface like the following:

interface State {
  a: string,
  b: string
}

And potentially formulate a generic type for the array that utilizes State as a partial application to both input and output types for each function within the array?

Answer №1

To establish a sequence of functions where each function relies on the output of the preceding one, you must define a function and overloads for every number of functions you wish to accommodate:

function chain<R1, R2, R3, R4>(fn1: ()=> R1, fn2: (a: R1) => R2, fn3: (a: R1 & R2) => R3, fn4: (a: R1 & R2 & R3) => R4) : [typeof fn1, typeof fn2, typeof fn3, typeof fn4]
function chain<R1, R2, R3>(fn1: ()=> R1, fn2: (a: R1) => R2, fn3: (a: R1 & R2) => R3) : [typeof fn1, typeof fn2, typeof fn3]
function chain<R1, R2>(fn1: ()=> R1, fn2: (a: R1) => R2) : [typeof fn1, typeof fn2]
function chain(...fns: Array<(a?: any)=> any>) : Array<(a?: any)=> any> {
    return fns;
}

const a =chain( // return types are not necessary.
    () => ({ a: 'alpha'}),
    ({ a })  => ({ b: 'beta' }),
    ({ a, b }) => ({ c: a, z:a }),
)

Answer №2

Not the best solution, but it does provide some level of support:

type TransformationFn<T> = (input: Partial<T>) => Partial<T> | Promise<Partial<T>>;
type Transformations<T> = TransformationFn<T>[]

interface Data {
  foo: string,
  bar: string
}

const transformations: Transformations<Data> = [
  () => ({ foo: 'value1'}),
  ({ foo }) => ({ bar: 'value2' }),
  ({ foo, bar }): {} => ({}),
]

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

React TypeScript throws an error when a Socket.IO object is passed to a child component and appears as undefined

Currently, I'm developing a simple chat application as part of my university course. The code below represents a work-in-progress page for this project. While I am able to get the socket from the server and use it in the main component without any is ...

Having trouble locating the asset at /home/runner/CDK_Test/frontend/frontendapp/build while executing CDK deploy with GitHub Action

When attempting to execute `cdk deploy` on GitHub Actions, I encountered an issue with finding the build from frontendapp. I double-checked the build path for any errors but found none. Interestingly, running `cdk deploy --all` locally successfully display ...

Issue in Typescript: The type 'RegExpMatchArray' cannot be assigned to a parameter of type 'string'

Here is the code snippet I am working with: import { persistState } from 'redux-devtools'; const enhancer = compose( applyMiddleware(thunk, router, logger), DevTools.instrument(), persistState( window.location.href.match(/[?&]debu ...

What advantages does subscribe() offer compared to map() in Angular?

I recently started exploring observables in angular2 and found myself puzzled over the decision to use map() instead of subscribe(). Let's say I am fetching data from a webApi, like so: this.http.get('http://172.17.40.41:8089/api/Master/GetAll ...

Exclude a specific field from a tuple

type ExampleTuple=[{name:'Alice',age:25},{name:'Bob',age:30}] type FilteredTuple=TupleOmit<ExampleTuple,'age'> // = [{name:'Alice'},{name:'Bob'}] type IncorrectType =Omit<ExampleTuple[number],&apo ...

Utilizing Ionic 2 and Angular 2 to integrate Google Maps and display multiple markers based on coordinates retrieved

I'm currently working on implementing multiple markers on a map within my Ionic 2 app. //Establishing connection to locations database this.db.connect(); let locations = this.db.collection('locations'); //Fetching all user ...

Using placeholders with inputs in an Angular2 table generated by ngFor

I have an array public example = [['hallo', 'fruit', 'rose'], ['apple','book']] Currently, I am working on creating a table of inputs. The values in this table depend on the specific part that I am usin ...

Creating Multiple Routes in a Single TypeScript and AngularJS Route File

I have built a module with TypeScript and AngularJS that includes multiple pages. I would like to use one TypeScript controller per page. How can I define multiple controllers in my routes? Currently, I have only defined one, but what if I have 6 or 7 co ...

Different ways to handle dialogs in React with TypeScript

I'm currently working on developing a modal component in React TypeScript and I'm facing some issues in determining the correct type for a reference of an HTML dialog element. import { useRef } from 'react' const MyModal: React.FC = () ...

Searching in TypeScript tables with Angular's search bar

I've successfully completed a basic CRUD application, but now I need to incorporate a Search Bar that can filter my table and display rows with matching letters. I'm unsure how to approach this in my component. I've seen examples using pipe ...

Troubleshooting Angular and Auth0: Understanding the issue with loginWithRedirect() always returning isAuthenticated$ as false

I have previously posted this issue on the Auth0 Community Help Forum, but I am yet to receive a response despite posting it 2 weeks ago. Here is the link to my original post: Currently, my setup includes angular/cli 15.1.1 and auth0/auth0-angular 2.0.1. ...

Utilizing Angular 10 to Transform a JSON Data into a Custom String for HTML Rendering

I have received a JSON response from my backend built using Spring Boot. The "category" field in the response can either be 1 or 2, where 1 represents Notifications and 2 represents FAQs. { "pageNumber": 0, "size": 5, "totalPages&q ...

Ways to collect particular tokens for delivering targeted push notifications to designated devices

When filtering the user's contacts, I ensure that only contacts with created accounts are displayed on the screen. This process helps in visually organizing the contact list. List<PhonesContacts> phoneContacts = snapshot.data; Lis ...

A Guide to Retrieving Parameters and Request Body using Express and Typescript

When I use the PUT method, I encounter this issue: const createFaceList = (req: Request<{faceListId : string}>, res: Response, next: NextFunction) => { console.log(req.body.name); console.log("faceListID = " + req.params.faceListId); a ...

Utilizing Conditional Aurelia Validation Based on Element's Display Status

Currently, I am in the process of setting up a license subscription form using Aurelia and the Aurelia Validation plugin. Within this form, there is a fieldset dedicated to personal information which contains mostly required fields that are validated by Au ...

An unexpected error occurred while running ng lint in an Angular project

I've encountered an issue while trying to run ng lint on my Angular project. After migrating from TSLint to ESLint, I'm getting the following error message when running ng lint: An unhandled exception occurred: Invalid lint configuration. Nothing ...

An issue occurred while attempting to differentiate the '[object Object]'. Angular-11 Application only accepts arrays and iterables for this operation

When using *ngFor, I am facing an issue with fetching data from my component.ts to my component.html Interestingly, the same method works for one class but not for another. Let's take a look at my service class: export class FoodListService { priv ...

Exploring the relationship between Typescript, RxJS, Ajax, undefined values

This particular question stands out due to the fact that despite similar issues being previously addressed, none of the existing solutions have proven effective. The problem at hand is as follows: There's a Typescript class that initiates an RxJS.aja ...

Adjusting the interface of a third-party TypeScript library

I am currently working on modifying a third-party interface. I'm curious about why this particular code is successful: import { LoadableComponentMethods as OldLoadableComponentMethods } from '@loadable/component'; declare module "load ...

What is the best way to define multiple variables in ionic 2 using Angular2 and TypeScript?

I'm brand new to working with ionic2/Angular2/Typescript. My project involves creating a wheel with eight slices, but I'm struggling with how to declare multiple variables. In JavaScript, I've declared them like this: function rand(min, max ...