Typescript: Dynamically assigning array type based on preceding array element

Can Typescript support the implementation of an infinite Array (not a Tuple) with a type that depends on the previous element of the array?

Here is a sample pseudo-typescript code:

class B<T, U> {}

function foo<X, Y>(...args: [B<X, Z0>, B<Z0, Z1>, B<Z1, Z2>, ..., B<ZN, Y>]) {}

foo<string, number>(new B<string, number>, new B<number, boolean>, new B<boolean, number>); // Correct
foo<string, number>(new B<string, number, new B<number, boolean>); // Incorrect
foo<string, number>(new B<string, number>, new B<boolean, number>); // Incorrect

What should be substituted for "

[B<X, Z0>, B<Z0, Z1>, B<Z1, Z2>, ..., B<ZN, Y>]
" to make this function? Is it feasible at all?

Your insight is appreciated!

Answer №1

Recently, I was faced with a similar issue that required creating a lengthy chain of streams where the output of one stream had to be the input of the next. Here's how I tackled it:

type SkipFirst<T extends any[]> = T extends [any, ...infer R] ? R : never
type GetOrFallback<Object, Key, Default = never> = Key extends keyof Object ? Object[Key] : Default
type StreamChain<Start, End, Inputs extends [Start, ...any[]], Outputs extends any[] = SkipFirst<Inputs>> = {
    [I in keyof Inputs]: DuplexConstructor<Inputs[I], GetOrFallback<Outputs, I, End>>
}

export function createStreamChain<Initial, Final, Pipes extends [Initial, ...any[]]>(
    ...streamTypes: [ReadableConstructor<Initial>, ...StreamChain<Initial, Final, Pipes>, WritableConstructor<Final>]
): Writable {
    const source = streamTypes[0]
    const middleStreams = streamTypes.slice(1, -1) as StreamChain<Initial, Final, Pipes>
    const sink = streamTypes[streamTypes.length - 1] as WritableConstructor<Final>

    let head = readable(source)
    middleStreams.forEach((pipe) => (head = head.pipe(duplex(pipe))))
    return head.pipe(writable(sink))
}

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

Angular Unit testing error: Unable to find a matching route for URL segment 'home/advisor'

Currently, I am working on unit testing within my Angular 4.0.0 application. In one of the methods in my component, I am manually routing using the following code: method(){ .... this.navigateTo('/home/advisor'); .... } The navigateTo funct ...

conflicting data types between typedef declaration and structure definition

I encountered a small issue in my code. I used typedef to declare a type in the file "single_list.h" and then implemented the structure for this type in "single_list.c". However, I'm getting a lot of conflicting type errors and I can't figure out ...

Instructions on how to populate an array of doubles with numbers ranging from 1 to 15

Is there a way I can achieve the same functionality using a loop? string[] titles = new string[] { "Alpha", "Beta", "Gamma", "Delta" }; List<double[]> x = new List<double[]>(); for (int i = 0; i < titles.Length; i++) { // Your code goes he ...

Deliberately choosing not to fulfill the Bluebird Promise

Here is a piece of code that needs to call a callback which may return a promise. The goal is to resolve the promise and log an error if it fails, without the caller knowing about it or waiting for the promise to fulfill. However, not returning the promise ...

JavaScript - convert the values of an array within a JSON object into separate strings

I am receiving a JSON object from an API, and my next step involves some string analysis of each key value. This process works perfectly for 90% of the objects I receive because the key values are strings. { ID: '0012784', utm_source: 'webs ...

Can a mapped union type be created in TypeScript?

Can the features of "mapped types" and "union types" be combined to generate an expression that accepts the specified interface as input: interface AwaActionTypes { CLICKLEFT: 'CL'; CLICKRIGHT: 'CR'; SCROLL: 'S'; ZOOM ...

Develop a cutting-edge TypeScript library that allows for seamless resolution of optional dependencies by the application

One of my recent projects involved creating a library that I published to a private npm repository. This library consisted of various utilities and had dependencies on other libraries, such as @aws-sdk/client-lambda. However, not all applications utilizin ...

Struggling with integrating Axios with Vue3

Can someone assist me in figuring out what is going wrong with my Axios and Vue3 implementation? The code I have makes an external call to retrieve the host IP Address of the machine it's running on... <template> <div id="app"> ...

Having issues with Vue 3 Typescript integration in template section

This particular project has been developed using the create-vue tool and comes with built-in support for Typescript. Key versions include Vue: 3.3.4, Typescript: 5.0.4 Here is a snippet of the code to provide context: // ComponentA.vue <script setup l ...

What is the best way to dynamically add data to a JSON file?

image of JSON file Just a heads up: I'm looking to add data directly without the need to write it to a .json file, perhaps by using Angularfire2 database. user = { name: 'Arthur', age: 21 }; const options = {Headers, responseType: &apo ...

Having difficulty altering the color of an element in Viewer

Currently, I am conducting a PoC and experimenting with changing the color of a selected element to red. Despite creating a class as shown below, I am facing issues where the elements do not change color when selected. I have attempted various examples fro ...

Avoiding the insertion of duplicates in Angular 2 with Observables

My current issue involves a growing array each time I submit a post. It seems like the problem lies within the second observable where the user object gets updated with a new timestamp after each post submission. I have attempted to prevent duplicate entr ...

Troubleshooting issue with React mapping an array of items in a modal window

My state implementation is working perfectly fine, except for a minor issue with the modal window. Within the state, I have utilized objects that are normally displayed (you can refer to the screenshot here). Please pay attention to the "Open modal" butt ...

"Use eslint to manage the integration of typescript with modules, regardless of type declarations

I'm in the process of upgrading eslint to v9 to work with next-json While following the official Getting started guideline, I realized that I need to include "type": "module" in the package.json file for it to function properly. ...

Capturing post image URLs from JSON data in Python for Tumblr storage

I am currently exploring ways to store multiple URL links in a Python array key or using other methods that allow for storing multiple URL links. In the dataset I am working with, each post may or may not contain multiple 'photos' image obje ...

Exploring methods in Firebase Cloud Functions to retrieve and modify values

I'm currently attempting to retrieve a value from a specific location in my database, add 1 to it, and then update it back. However, I keep encountering various errors, with the most recent being: TypeError: Cannot read property 'update' of ...

Currently, I am in the process of mastering data fitting in Python using importance sampling. My main focus is on sampling x and y values and determining their respective weights. However, I have encountered

My current project involves sampling x and y from a proposal distribution function, calculating the weights for each sample, and generating 10 sets of n = 10,000 samples. I have received an array of 55 values for radius as well as mu and sigma parameters, ...

I am completely puzzled by the way a value can differ outside of a for-loop compared to inside

When I print out a pointer array value (specifically the first value for testing purposes), it shows 3 when printed outside the for loop. However, when I try to print it within the for loop, it displays 0 instead. I've checked various steps during th ...

Create a new interface to encapsulate the intersect type

Everywhere I look, I seem to be writing the following: product: Product & { id: string; }; Is there a way for me to simplify this to: product: WithId<Product>; I attempted to create an interface like the one below, but encountered issues with ...

transforming a MATLAB array stored in a .MAT file into a C++ array

In my MATLAB code, I have a 2-D double-precision array with specific data. To utilize this array in c++, I decided to save it in a mat-file. Although I am aware that MATLAB offers c functions like matdsgn and matOpen for reading mat-files in c++, I am un ...