Is it possible to designate a Typescript generic type as a tuple with equal length to that of another tuple?

Imagine having a function that takes in a dataset which is an array of (identically-typed) tuples:

type UnknownTuple = any[]
function modifyDataStructure<T extends UnknownTuple>(list: T[]) {
   ...
}

The goal is to define a second argument with the same length as the tuples, but with different types (for example, string labels):

const entries = [
  [7, 'Moo',    true],
  [3, 'Sophie', false],
  [4, 'Tip',    true]
] 

modifyDataStructure(entries, ['age', 'name', 'is_fuzzy']) // success
modifyDataStructure(entries, ['age', 'name'])             // error

How can we specify the type for the second argument?

type UnknownTuple = any[]
function modifyDataStructure<T extends UnknownTuple>(list: T[], labels: ???) {
   ...
}

This question post "Typescript length of a generic type" is quite similar, but involves varargs and higher-order functions, making it more complex. Here, I aim to simplify and focus on clarifying this scenario.

Answer â„–1

To convert a tuple into another tuple of the same length, you can utilize a mapped type:

const data = [
  [7, 'Moo',    true] as const,
  [3, 'Sophie', false] as const,
  [4, 'Tip',    true] as const 
]
type MysteryTuple = readonly any[]
type Titles<T> = {
    [P in keyof T]: string
}
function convertTuple<T extends MysteryTuple>(list: T[], titles: Titles<T>) {
   ///...
}
convertTuple(data, ['age', 'name', 'is_fuzzy']) // works fine
convertTuple(data, ['age', 'name']) // results in an error

Playground Link

If you'd like convertTuple to infer tuple types rather than arrays, adjust the constraint to [any] | any[], but remember to specify object literals inline when calling your function

function convertTuple<T extends [any] | any[]>(list: T[], labels: Titles<T>) {

}
convertTuple([
  [7, 'Moo', true],
  [3, 'Sophie', false],
  [4, 'Tip', true]
], ['age', 'name', 'is_fuzzy']) // ok

Playground Link

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

After the rendering process, the React Component member goes back to a state of

One issue I encountered is related to a component that utilizes a separate client for making HTTP requests. Specifically, when trying to use the client within a click event handler, the call to this.client.getChannel() fails due to this.client being undefi ...

There are no call signatures available for the unspecified type when attempting to extract callable keys from a union

When attempting to write a legacy function within our codebase that invokes methods on certain objects while also handling errors, I encountered difficulty involving the accuracy of the return type. The existing solution outlined below is effective at cons ...

Angular is throwing an error stating that the type '{ }[]' cannot be assigned to the type '[{ }]'

I'm in need of assistance and clarification regarding the error I encountered in my application... When I receive a JSON response from an API with some data that includes an array of products, I aim to extract these products (izdelki) from the array, ...

Error: The version of @ionic-native/[email protected] is not compatible with its sibling packages' peerDependencies

When attempting ionic cordova build android --prod, the following error occurred: I have tried this multiple times. rm -rf node_modules/ rm -rf platforms/ rm -rf plugins/ I deleted package.lock.json and ran npm i, but no luck so far. Any ideas? Er ...

What is the reason a type is able to cast to an indexed collection when it is inferred, while an explicit type that seems identical is

I am puzzled by why my inferred types are considered as instances of my more general collection type while my explicit types are not. My goal was to: Have a specific part of my application work with tightly defined collections (e.g., IParents vs IBoss ...

How to inject a regular class in Angular2 without the @Injectable decorator

angular: 2.0.0-beta.9 Can we inject a non-@Injectable class into a component? For instance, if this class originates from an external Third party library. ...

The improved approach to implementing guards in Angular

I am currently looking for the most effective way to utilize Angular "guards" to determine if a user is logged in. Currently, I am checking if the token is stored. However, I am wondering if it would be better to create an endpoint in my API that can verif ...

How can one use an Angular Route to navigate to a distinct URL? Essentially, how does one disable matching in the process?

I'm working on a front-end Angular application and I need to add a menu item that links to an external website. For example, let's say my current website has this URL: And I want the menu item in my app to lead to a completely different website ...

The paths configuration in tsconfig.json is not functioning as anticipated

I've been encountering a module not found error while trying to work with jasmine-ts. To troubleshoot, I decided to use tsc and inspect my folder structure: \src\app\... \src\tests\... To address this issue, I created a ...

Is it possible to create an instance in TypeScript without using class decorators?

As per the definition on Wikipedia, the decorator pattern enables you to enhance an object of a class with additional functionalities, such as: let ball = new BouncyBall(new Ball()) The Ball object is adorned with extra features from the BouncyBall class ...

Understanding Angular's Scoping Challenges

I have a function that retrieves an array and assigns it to this.usStates. main(){ this.addressService.getState().subscribe( (data:any)=>{ this.usStates = data; if(this.usStates.length===0) { this.notificationServic ...

Combining Vue-Test-Utils with TypeScript typings for wrapper.vm

So, I ran into an interesting situation. Has anyone ever worked with typescript + vue-test-utils and attempted to change a value for testing purposes like this: wrapper.vm.aCoolRefValueToManipulate = 'something much cooler'? I gave it a shot, a ...

Encountering issues while attempting to utilize pdf2json in a TypeScript environment

When attempting to import pdf2json (3.0.1) into my Node project using TypeScript, I encountered the following error: "Could not find a declaration file for module 'pdf2json'." I also tried installing @types/pdf2json for TypeScript but found tha ...

Submit information by utilizing' content-type': 'application/x-www-form-urlencoded' and 'key': 'key'

Attempting to send data to the server with a content-type of 'application/xwww-form-urlencode' is resulting in a failure due to the content type being changed to application/json. var headers= { 'content-type': 'applica ...

Writing TypeScript, Vue, and playing around with experimental decorators

After creating a Vue project through Vue-CLI v3.0.0-beta.15, the project runs smoothly when using npm run serve. However, TypeScript displays an error message stating that support for decorators is experimental and subject to change in a future release, bu ...

Can someone explain the distinction between 'return item' and 'return true' when it comes to JavaScript array methods?

Forgive me for any errors in my query, as I am not very experienced in asking questions. I have encountered the following two scenarios :- const comment = comments.find(function (comment) { if (comment.id === 823423) { return t ...

How does the type of the original array influence the inferred types of the destructured array values?

let arr = [7, "hello", true]; let [a, ...bc] = arr; typeof bc : (string | number | boolean)[] why bc type is (string | number | boolean) expect: because bc = ["hello", true], so bc type should be (string | boolean)[] ...

Angular is used to call a function that captures a specific div and then waits for the capture to be completed before

I'm facing a challenge where I need to handle the capturing of a div using a method called capture() within another method. Take a look at the code snippet below: theimage; // declaring the variable callcapture() { // perform certain actions t ...

Removing data from a table using an identifier in Typescript

Recently, I have made the switch from using Javascript to TypeScript. However, I am facing an issue while trying to delete data from a table in my code. Whenever I attempt to delete data, I encounter this error message: Property 'id' does not e ...

What distinguishes between a public variable declared as var: any = []; versus a public variable declared as var: any[] =

I'm seeking clarification on the distinction between the following: public var: any = []; // versus public var: any[] = []; ...