Using TypeScript: Incorporating a map function in type declarations

My current situation involves the following types:

type Value = boolean | number | string

class Struct<T extends Value[] = Value[]> {

    constructor(fmt: string) { }

    pack(...args: T): Buffer { }

}

I am seeking guidance on how to replace <???> with a list of the Value[] used by each Struct passed to the constructor in the snippet below:

class StructConcat<T extends Struct[]> {

    constructor(...structs: T) { }

    pack(...args_list: <???>) { }

}

// example:
const a: HeadStruct = new Struct<[number]>('<I')
const b: VectorStruct = new Struct<[number, number, number]>('<3f')
const concat = new StructConcat(a, b)

Ultimately, I want the StructConcat.pack function to be limited to this form:

concat.pack([1], [2, 3, 4])

So far, the closest solution I have found is:

(T[number] extends Struct<infer K> ? K : never)[]
but it still outputs
([number] | [number, number, number])[]
instead of
[[number], [number, number, number]]
as desired.

Is it possible within TypeScript's typing system to achieve this?

Answer №1

In the TypeScript version 3.1 and above, you now have the ability to utilize tuples within mapped types:

type Value = boolean | number | string

class Struct<T extends Value[] = Value[]> {

    constructor(fmt: string) { }

    pack(...args: T): Buffer { }

}

type ExtractValueFromStruct<T> = T extends Struct<infer V> ? V : never
type MapStructTuple<T extends Struct[]> = { 
    [P in keyof T]: ExtractValueFromStruct<T[P]>
}

class StructConcat<T extends Struct[]> {

    constructor(...structs: T) { }

    pack(...args_list: MapStructTuple<T>) { }

}

// For instance:
const a= new Struct<[number]>('<I')
const b= new Struct<[number, number, number]>('<3f')
const concat = new StructConcat(a, b)
concat.pack([1], [1, 2, 3])
concat.pack([1], [1, 2, 3, 4]) // This will result in an error

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

Transformation of Python code into Blockly blocks

As the founder of edublocks.org, I am interested in adding Python to Blocks functionality on the platform. At the moment, users can only transition from Blocks to Python. Is there anyone who has experience with this and can provide guidance on how to achi ...

Implementing Asynchronous context tracking within a Remix application utilizing Express as the server

Utilizing Remix with Express as the server, I aim to develop an Express middleware that establishes an async context to grant all downstream functions (especially those in the "backend" Remix code) access to this context within the scope of a single reques ...

The function mustAsync onSuccess is not present in this type (typescript)

I currently have 2 mutations that are functioning well. However, I encountered an issue when attempting to implement onSuccess and invalidateQueries. The error message displayed is as follows: Property 'mutateAsync' does not exist on type '{ ...

Using TypeScript in combination with Angular for implementing CORS protocol

As I try to send a request to my REST endpoint, the following code is executed: this.http.request(path, requestOptions); The path is set to: http://localhost:8082/commty/cmng/users and the requestOptions are as follows: { headers: { user: "sdf", pas ...

Compilation of Angular 6 project is failing due to error TS1005: Expected ',' instead of the symbol used

I keep encountering an error message whenever I try to compile my code. ERROR in src/app/form/form.component.ts(22,39): error TS1005: ',' expected. Below is the snippet of code where the error is pointing: import { Component, OnInit } from &ap ...

Typescript's return type can be autocompleted based on the input object provided

Update: Shoutout to for providing the completed version which can be accessed here: https://github.com/web-ridge/react-ridge-translations/blob/main/src/index.ts I've been developing a translation library for React / React Native, but I'm facing ...

Configuring the React Typescript router to support username-based URLs should be done in a way that does not cause conflicts with other routes

I am looking to display a user's profile on a URL format such as www.domain.com/<userName> and load the component ShowProfile. I want to ensure that terms is not mistaken for a username, so if I visit www.domain.com/terms, I do not want to load ...

Apply dynamic directives to an HTML string fetched from the server

Receiving a string of HTML from the server with custom directive attributes that Angular should render, but struggling to make the directives work. Is it possible to load HTML containing custom directives? I've been using DomSanitizer.bypassSecurityT ...

Why is my input field value not getting set by Angular's patchValue function

I've been attempting to populate an input field using the form group with patchValue(), but for some reason, the input remains empty. Here's a snippet of my code... component.html <form [formGroup]="createStoreForm" (ngSubmit)="createStor ...

Angular error TS2322 arises when attempting to assign a type of 'Observable<{}>' with the share() operator

Currently diving into Angular 5, I've been exploring the Observable/Observer pattern to facilitate event sharing and data changes among subscribers. Below is a snippet of the code in question: ... @Injectable() export class NidoService { ... eve ...

What could be the reason for mat-autocomplete not displaying the loading spinner?

Currently, I am integrating Angular Material into my Angular 11 project. One of the pages includes a mat-autocomplete component where I want to display a loading spinner while waiting for a request. Here is the code snippet I am using: component.ts this. ...

Troubleshooting problems with building an Angular project containing Angular Slickgrid

After successfully migrating my project from Angular 13 to Angular 17 and updating angular-slickgrid from version 4.1.4 to 7.5.0, I am facing a build error that I cannot resolve. I have addressed all other errors except for one: When compiling with Angular ...

Looking to determine if two elements exist within an array? Seeking a boolean result based on their presence

Consider the following array of objects: quesListArray = [ { QuestionTypeID : 1, QuestionTypeName : 'Rating' }, { QuestionTypeID : ...

having difficulty accessing the value within the Angular constructor

My current issue arises when I click on a button and set a value within the button click method. Despite declaring the variable in the constructor, I am unable to retrieve that value. The code snippet below demonstrates this problem as I keep getting &apos ...

A step-by-step guide on bundling a TypeScript Language Server Extensions LSP using WebPack

Currently, I am working on a language server extension for vs-code that is based on the lsp-sample code. You can find the code here: https://github.com/microsoft/vscode-extension-samples/tree/master/lsp-sample My challenge lies in WebPacking the extension ...

Firebase data not appearing on screen despite using the async pipe for observables

My current challenge involves accessing data based on an id from Firebase, which comes back as an observable. Upon logging it to the console, I can confirm that the Observable is present. However, the issue arises when attempting to display this data on th ...

Is it feasible to replicate an error in TypeScript with certain modifications?

Currently, I'm facing a challenge where I need to utilize Sentry.captureException with an error that I have received. However, before doing so, I am attempting to modify the error message. Despite spending considerable time searching for a solution, I ...

Learn how to connect a formArray from the parent component to the child component in Angular with reactive forms, allowing you to easily modify the values within the formArray

In my parent component, there is a reactive form with controls and a form group. When the user selects a playerType from a dropdown menu, I dynamically add a formArray to the formGroup. This form array will contain either 2 or 3 form groups based on the p ...

Error message appears when using TypeScript with a React Material table showing a generic type error

I am currently attempting to implement react-material in a Typescript project. As a newcomer to Typescript, I am encountering some errors that I am unsure how to resolve. In this gist, I am trying to create a reusable React component (Please view the gis ...

Challenge with the scope of 'this' in Typescript

Whenever I invoke the findFromList function from a component, it triggers this particular error message: ERROR TypeError: Cannot read property 'searchInArray' of undefined at push../src/app/shared/services/filter.service.ts.FilterService ...