Guide to creating a generic type in Typescript that includes constraints to extend an iterable

I am currently working on writing a specific type of Pagination:

type Pagination<I extends Iterable> = Readonly<{
  seek: number;
  limit: number;
  total: number;
  items: I;
}>;

This allows users to utilize:

Pagination<Map<number, any>>

However, there seems to be an issue because Iterable also requires a generic parameter.

Therefore, I am now using:

type Pagination<I> = Readonly<{
  seek: number;
  limit: number;
  total: number;
  items: Iterable<I>;

}

While this solution works, the type signatures are limited to Pagination<number> without further constraints on the type of iterable to be used.

Answer №1

Instead of specifying the item type, you can utilize the generic parameter for the iterable itself using T extends Iterable<any>

type Pagination<I extends Iterable<any>> = Readonly<{
  seek: number;
  limit: number;
  total: number;
  items: I;
}>;

Note: If you do require the item type, a conditional type can be used to extract it:

type Pagination<I extends Iterable<any>> = Readonly<{
  seek: number;
  limit: number;
  total: number;
  items: I;
  current: I extends Iterable<infer Item> ? Item: never
}>;

declare let map: Pagination<Map<string, number>>
map.current // [string, number]

declare let arr: Pagination<string[]>
arr.current // string

Play

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

Typescript method for handling empty JSON responses

Query: How can I filter out the array items that do not contain images in this JSON response? I am new to Angular and Typescript. this.music.searchArtists(this.searchQuery).subscribe( data =>{ this.results = data.artists.items; console.log(thi ...

Tips for transfering variables from an electron application to the backend of an Angular project

My goal is to develop a website and desktop application using the same code base. However, due to some minor differences between the two platforms, I need a way for my Angular app to distinguish whether it has been called from the web or from Electron. I& ...

Issue: The code is throwing an error "TypeError: Cannot read property 'push' of undefined" in the JavaScript engine "Hermes

Can anyone assist me with filtering an array of objects in a TypeScript React Native project using state to store array values and filter objects in the array? Having trouble with the following error in the mentioned method: LOG after item LOG inside ...

Angularjs 2 Error: Unable to access the 'infos' property of an undefined object using the Http Client

I've been working on an AngularJS app for about a week now, developing a backoffice application for my service. My main challenge lies in using data retrieved from a remote server. I have 4 HTTP GET requests in my app - 2 of them fetching lists of us ...

Struggling to modify a string within my React component when the state is updated

Having a string representing my file name passed to the react-csv CSVLink<> component, I initially define it as "my-data.csv". When trying to update it with data from an axios request, I realize I may not fully understand how these react components w ...

Creating callback functions that vary based on input variables

Consider the following code snippet, which may seem somewhat contrived: arbitraryFunction( // Input that is dynamically generated [ returnValue("key1", "a"), returnValue("key2", 1), returnValue ...

Tips on ensuring that the Google Maps marker remains in the center as you drag the map with the AGM component

I've implemented AGM (Angular Google Maps) in my Ionic Project to showcase Google Maps, and I'm looking to have the marker stay centered on the map even when it is dragged. Is there a way to achieve this with AGM? Please let me know if I have mad ...

What kind of Typescript type should be assigned to setState when passed to the component?

In my setup, I have a variety of Parent components: const ParentOne = () => { const [error, setError] = useState<{ one: boolean }>({ one: false }); ...omit return ( <> <Child setErr={setError} name={"one"} /> </> ...

Manipulating CSS styles through Javascript with passed parameters

I need a feature that allows users to pick the color of the buttons displayed on the website. Currently, I am working with Angular 6 and JavaScript to achieve this functionality. I am focusing on setting the primary color, affecting buttons with the Bootst ...

Typescript - ensure only one specific value is in an array of length N

Is there a way to require the 'foo' literal, while allowing the array to have any shape (i.e. not using an X-length tuple with pre-defined positions)? type requireFoo = ??? const works: requireFoo = ['bar','foo'] //This shoul ...

Tips for utilizing chodorowicz / ts-debounce effectively

Looking to utilize the debounce function provided by the ts-debounce package (available at here) in my typescript project. However, struggling to find a concrete example of its usage in typescript. Would greatly appreciate any help or guidance on this ma ...

Mastering mapped types to replace properties in Typescript

I have created a Factory function where it takes an object as input and if that object contains specific properties, the factory transforms those properties into methods. How can I utilize mapped Types to accurately represent the type of the resulting obj ...

What is the best way to incorporate the active class in the initial div utilizing *ngFor within Angular 7?

I've got a series of carousel-item divs being repeated using *ngFor. Now, I'm trying to figure out how to dynamically add the active class to just the first div (carousel-item). Any suggestions on how to achieve this in Angular 7? component.html ...

Changing function arguments in TypeScript using the spread operator

Could the Tuple spreading syntax in Typescript be utilized to consolidate these function overloads? The challenge lies in the necessity to refactor the function arguments into new types. type Type = TString | TNumber type TString = { tag: 'string&apos ...

User's information will only be updated once the page is refreshed

I am encountering an issue with displaying two ul elements based on user login status. When I log in, the first ul is shown immediately, but the second ul is only displayed after a page refresh. Initially, the value in "accountService.currentUser" is null ...

After compiling the code, a mysterious TypeScript error pops up out of nowhere, despite no errors being

Currently, I am delving into the world of TypeScript and below you can find the code that I have been working on: const addNumbers = (a: number, b: number) => { return a + b } Before compiling the file using the command -> tsc index.ts, the ...

Issue with TypeScript: variable lacks an initializer and is not explicitly assigned within the constructor

Code: class Example { private server: string; constructor() { this.setServer(); } setServer(): void { this.server = 'server'; } } new Example(); Error: ⨯ Unable to compile TypeScript: src/index.ts:309:13 ...

Creating an object in JavaScript using an array type初始化数组类型为对象javascript

In my code, there is an interface defined as Products export interface Products{ category: string; imageUrl: string; price: number; title: string; } Within my component, I have a variable named products which is an array of type Product ...

How can I verify the value of a class variable in TypeScript by using a method?

I need a more concise method to inform TypeScript that my client has been initialized (no longer null). While I have achieved this functionality, the current implementation seems unnecessarily verbose. Here is how it currently looks: export abstract class ...

Having trouble uploading images using Ionic/Angular to a PHP script

I've been working on incorporating image uploading functionality into my Ionic app. Despite reading multiple tutorials, I haven't been able to get it up and running successfully. I'm specifically aiming for the app to work smoothly in a web ...