What is the process for parameterizing a tuple in coding?

In my scenario, I have a tuple with interrelated types. Specifically, it involves an extractor function that retrieves a value, which is then used as input for another function.

What I envision conceptually looks like this code snippet, although it does not compile:

const a: <T>[(v:any) => T, (t:T) => void] = [ ... ]

The purpose of this setup is to handle incoming RPC messages of type any, in conjunction with an API that uses specific argument types. Essentially, I aim to create a "wiring plan" consisting of pairs of extractor functions and corresponding API functions.

export interface API = {
    saveModel : (model:Model)    => Promise<boolean>,
    getModel  : (modelID:string) => Promise<Model>,
}

const api: API = { ... }

// The desired tuple type definition specifies the relationship between the second and third elements.
type WirePlan = [[string, (msg:any) => T, (t:T) => Promise<any>]]

const wirePlan: WirePlan = [[
  ['saveModel', (msg:any) => <Model>msg.model   , api.saveModel],
  ['getModel' , (msg:any) => <string>msg.modelID, api.getModel],
]

const handleMessage = (msg) => {
  const handler = wirePlan.find((w) => w[0] === msg.name)
  const extractedValue = handler[1](msg)
  return handler[2](extractedValue)
}

I can find alternative solutions to the problem at hand, but it occurred to me that there might be nuances about tuples that I haven't fully grasped.

Answer №1

In essence, my objective is something similar to the code snippet below, which unfortunately does not compile:

const a: <T>[(v:any) => T, (t:T) => void] = [ ... ]

Ironically, what you actually need is quite the opposite of your initial approach. Based on the concept of function types, a: <T>(t: T) => T would indicate a function that applies universally across all types. This declaration suggests a universal quantifier, where the implementation of a remains oblivious to the specific type T; instead, it's up to the user of a to define T. Attempting this with your tuple could lead to negative consequences since the inner functions are expected to produce values of type

T</code regardless of its actual definition, resulting in potential errors or infinite loops.</p>

<p>What you're actually in search of is known as existential quantification. With an expression like <code>a: ∃T. [(v:any) => T, (t:T) => void]
, you specify that a embodies a certain type
T</code. While the internal workings of <code>a
have full knowledge of this type and can manipulate it accordingly, any external users of a remain unaware of its specifics. Essentially, this scenario reverses the dynamics compared to universal quantifiers. Despite TypeScript lacking built-in support for existential types, there are ways to mimic this functionality through various workarounds.

type WirePlanEntry = <R>(user: <T>(name: string, reader: (msg: any) => T, action: (t: T) => Promise<any>)) => R
type WirePlan = WirePlanEntry[]

The complexity of these constructs might seem daunting initially, but they deliver a powerful capability set once analyzed thoroughly. These components offer immense flexibility when dealing with unknown type scenarios and provide a robust foundation for handling different data structures efficiently.

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

What are the best practices for handling dynamic content internationalization in Angular?

According to Angular.io, the i18n tag is used to mark translatable content. It should be placed on every element tag that requires translation of fixed text. Now, what if we have an element with dynamic content? For example, consider a table displaying a ...

The Lenis smooth scrolling feature (GSAP) is not functioning properly

I have encountered an issue with the smooth scrolling feature of gsap causing a delay on my website. This problem is only resolved when I manually go into the browser settings and disable smooth scrolling by navigating to chrome://flags/#smooth-scrolling ...

Tips and tricks for setting up a functional react select component using Material UI

Having an issue with React Select material UI where the dropdown select is not functioning properly. The popup does not open up as expected. I am looking to display react select in a modal dialog box. import MenuItem from "@mui/material/MenuItem" ...

Managing Observable<Person[]> in ng-bootstrap typeahead instead of Observable<string[]>: a complete guide

I'm new to Angular/Typescript and have a question. I recently tried out the example from Wikipedia in ng-bootstrap typeahead. Instead of using the Wikipedia call, I decided to use a custom REST service that has the following GET endpoint: GET /pers ...

Ignoring the no-unused-vars rule from StandardJS even though variables are being used

Within my Typescript React project, I have declared the following: export type NavState = { mounted: boolean } I then proceeded to use this within a component like so: import { NavState } from '../../models/nav' class Nav extends React.Compon ...

how to send both the useState setter and object as props to a child component in React using TypeScript

Having an issue with passing useState setter and object (both together) to the child component. Successfully passed the object by spreading it like this {...object}, but unsure of the syntax to pass the setter along as well. Here's a code example: < ...

Angular application code modifications do not reflect in the browser

After making changes to the HTML file of an Angular component, the browser does not reflect those changes when connected to localhost. Even though the old string is no longer present in the project, the browser continues to display it. Interestingly, openi ...

Strategies for ensuring that code does not execute in Angular until the API response has been received

Currently, I am facing an issue where I need to wait for data from an API in order to set the value of a variable and use it in an if condition. The problem lies in my uncertainty about how to properly handle this asynchronous task using async and await. ...

Issue with displaying data using a custom pure pipe and boolean in ngIf condition

For my current web project, I require a friendship/follow feature. There are two roles involved: admins and regular users. Regular users have the ability to follow other users, while admins do not possess this capability. When a user wishes to follow anot ...

Angular2: Ensuring Sequential Execution Line by Line - A Comprehensive Guide

I have a designed an Angular2 Navbar Component that features a logout button: import { Component, OnInit } from '@angular/core'; import { LoginService } from '../login.service'; import { Router } from '@angular/router'; @Co ...

Fixing prop passing issues in Vue.js components to prevent errors

My Vue-cli install with TypeScript is set up to render JSX using a boilerplate. However, I am facing an issue when trying to pass a property to the HelloWorld component. Here's what my code looks like: export default Vue.extend({ name: 'App&apo ...

"Element of design focused on style and arrangement

After reviewing the material ui documentation located at https://material-ui.com/components/typography/ I attempted to utilize the Typography component in the following manner: <Typography variant="h1" component="h1"> Hello World </Typography& ...

Nest is unable to resolve the dependencies of the ItemsService. Ensure that the required argument at index [0] is present within the AppModule context

After following the Nest JS Crash tutorial from a Youtube Link, I encountered an error when importing an interface in the service. Nest seems unable to resolve dependencies of the ItemsService. It's important to ensure that the argument at index [0 ...

Make changes to an array in Javascript without altering the original array

I currently have an array : let originalArr = ['apple', 'plum', 'berry']; Is there a way to eliminate the item "plum" from this array without altering the originalArr? One possible solution could be: let copyArr = [...origin ...

The npm warning indicates that the file node_modules/.staging/typescript-8be04997/lib/zh-CN/diagnosticMessages.generated.json does not exist due to an ENOENT error

I am currently in the process of running npm install on a Linux machine where I do not have sudo access. Unfortunately, I have a machine-specific package.json and package-lock.json that cannot be changed. However, I encountered some errors during the insta ...

Leveraging Typescript Generics for limiting the input parameter of a function

Issue I have developed a Typescript package to share types between my backend node firebase cloud functions and frontend React client that accesses them. Provided below are examples of the types: interface FirstFunctionInput { x: number } interface Sec ...

What is the best way to display various components based on the user's device type, whether it be web

How can I use Angular 7, TypeScript, bootstrap, ngx-bootstrap, etc., to switch between components based on the user's device (desktop vs mobile)? I have noticed that many websites display different components when resized. I wonder if these are simpl ...

Using Angular2 and Typescript to declare a variable of type "any" can result

Hello StackOverflow community, I am encountering an issue with my JavaScript code where a global variable is sometimes not defined. I have a configuration class in Angular2 that imports this global variable using 'declare var any'. Within the cl ...

Is it no longer possible to instantiate an object using the syntax <interface>{}?

There seems to be an issue with the code snippet below when run in the TypeScript playground: interface Person { name: string; age: number; } const makePerson= function(name : string, age : number) : Person { let obj = <Person>{} ...

At what point do we employ providers within Angular 2?

In the Angular 2 documentation, they provide examples that also use HTTP for communication. import { HTTP_PROVIDERS } from '@angular/http'; import { HeroService } from './hero.service'; @Component({ selector: 'my-toh&ap ...