TypeScript: defining a custom type with a collection of properties following a consistent pattern

I am looking for a way to create a type that can accommodate any number of properties following a predefined pattern, like so:

type Values = {
  id: number;
  id1?: number;
  id2?: number;
  id3?: number;
  // ...
  somethingElse: string;
  anotherOne: number;
};

However, since I don't know the exact amount of ids in advance, I was wondering if there is a solution similar to this:

// pseudo-code
type Values = {
  id: number;
  [`id${index}`?: number];
  somethingElse: string;
  anotherOne: number;
};

This way, I could avoid using [k: string]: number.

If such an approach doesn't exist, what would be the most efficient and effective way to achieve a similar outcome without having to manually add numerous idX properties?

Answer №1

Utilizing a template literal type with a number within an index signature allows for specifying a pattern that properties must follow:

type Values = {
  id: number;
  [key: `id${number}`]: number
  somethingElse: string;
  anotherOne: number;
} 

let v:Values = {
  id: 0,
  somethingElse: "",
  anotherOne: 0,
  id0: 1,
  id22:1,
}

let v2:Values = {
  id: 0,
  somethingElse: "",
  anotherOne: 0,
  id0: 1,
  id22:1,
  bad: 0,
}

Explore Playground

This feature is supported in TS 4.4 and higher (PR)

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

Encountering a TypeScript error in Next.js: The 'Options' type does not align with the 'NavigateOptions' type

My code snippet: import { useRouter } from 'next/navigation'; interface Options { scroll: boolean; } const Component = () => { const router = useRouter(); const updateSearchParams = () => { const searchParams = new URLSearchPa ...

Due to the feature in VISUAL STUDIO CODE that presents folders and subfolders at the same level

While working on my Angular project, I encountered an issue with creating a subfolder within a folder. Despite trying the same process in Windows Explorer, I faced the same problem of them appearing on the same level. What could be causing this discrepan ...

Unclear error message when implementing union types in TypeScript

Currently, I am attempting to define a union type for a value in Firestore: interface StringValue { stringValue: string; } interface BooleanValue { booleanValue: boolean; } type ValueType = StringValue | BooleanValue; var value: ValueType = { bo ...

The typescript error TS2339 is triggered by the property 'webkitURL' not being found on the 'Window' type

Currently utilizing Angular 2 in a project that is compiled with TypeScript. Encountering an issue when attempting to generate a blob image: Error TS2339: Property 'webkitURL' does not exist on type 'Window' The TypeScript code causi ...

Exploring the Differences between Angular's Http Module and the Fetch API

While I grasp the process Angular uses for HTTP requests, I find myself leaning towards utilizing the Fetch API instead. It eliminates the need to subscribe and unsubscribe just for a single request, making it more straightforward. When I integrated it int ...

What is the best way to create an optional object parameter in Typescript?

I'm working on a function that looks like this: const func = (arg1: string, { objArg = true }:{ objArg: string }) => { // some code } Is it possible to make the second parameter (an object) optional? ...

Tips for using Firebase Parameterized configuration with Typescript when setting the region() on a Firebase Function

Based on this documentation, I am attempting to utilize a Firebase Parameterized configuration directly within the region() config for a function. My .env file looks like this: LOCATION = 'australia-southeast1'; And my config file is structured ...

The enum cannot be assigned a type of 'string | null'

Within my ProductGender enum, I have: enum ProductGender { Men, Women, } In my getProducts service: public getProducts( gender: ProductGender, category: ProductCategory ): Observable<IProductInterface[]> { return this.httpPro ...

Validating forms using TypeScript in a Vue.js application with the Vuetify

Currently, I am attempting to utilize Vue.js in conjunction with TypeScript. My goal is to create a basic form with some validation but I keep encountering errors within Visual Studio Code. The initial errors stem from my validate function: validate(): v ...

Contrasting {} and {} as any in TypeScript

Seeking clarity on TypeScript, what sets apart (foo and foo2) from (foo3 and foo4)? (foo and foo2) as well as (foo3 and foo4) produce identical results, yet during compilation, a red underline appears under foo2 and foo3. https://i.stack.imgur.com/lWaHc. ...

The conversion to ObjectId was unsuccessful for the user ID

I'm looking to develop a feature where every time a user creates a new thread post, it will be linked to the User model by adding the newly created thread's ID to the threads array of the user. However, I'm running into an issue when trying ...

How can I retrieve an array from an object containing both a property and an array in TypeScript?

One of my objects always consists of a property and an array. When I use the console.log(obj) method to print it out, it looks like the following example: ProjectName: MyTest1 [0] { foo: 1, bar: 2} [1] { foo: 3, bar: 4} [2] { foo: 5, bar: 6} Alternat ...

Troubleshooting a child process created by electron in Visual Studio Code

I am currently in the process of developing an electron application using typescript and webpack. I have encountered a specific debugging issue with vscode that I would like some assistance with: Context: The main process initiates a child process by call ...

Encountering a net::ERR_EMPTY_RESPONSE error while trying to use the DELETE Method in Angular 4

I have been using the following method to delete data: return this.http.delete(this.ApiURL, new RequestOptions({headers: headers,body: body })) .map((res: Response) => res.json()); However, I encountered the net::ERR_EMPTY_RESPONSE error. Interestingl ...

There was an issue with matching the call for formatting the start date to "dd MMMM yy" in the function

Hey there, while deploying my project, I encountered this error: Error: No overload matches this call. Overload 1 of 4, '(value: string | number | Date): Date', resulted in the following error: Argument with type 'string | string[] | ...

TypeScript enum type encompassing all potential values

One thing I have learned is that keyof typeof <enum> will give us a type containing all the possible keys of an enum. For example, if we have enum Season{ WINTER = 'winter', SPRING = 'spring', SUMMER = 'summer', AUT ...

What is the best way to eliminate any extra spaces from a string using typescript?

Currently in my Angular 5 project, I am encountering an issue with using the .trim() function in TypeScript on a string. Despite implementing it as shown below, no whitespace is being removed and also there are no error messages appearing: this.maintabinf ...

The TypeScript error message indicates that a value typed as 'string | undefined' cannot be assigned to a type 'string'

In my TypeScript-based React application where I am utilizing material-ui for components, I am currently working on creating a wrapper for material-ui's input. Here is the code snippet: import FormControl, { FormControlProps } from "@material-ui/core ...

The object literal's property 'children' is assumed to have a type of 'any[]' by default

Is there a way to assign the property myOtherKey with any value? I encountered a Typescript error that says.. A problem occurred while initializing an object. The property 'children' in the object literal implicitly has an array type of 'a ...

Retrieving information from a JSON object in Angular using a specific key

After receiving JSON data from the server, I currently have a variable public checkId: any = 54 How can I extract the data corresponding to ID = 54 from the provided JSON below? I am specifically looking to extract the values associated with KEY 54 " ...