What is the best naming convention for a TypeScript generic index signature interface?

Is there a specific term for the interface that includes a string index and generic type?

interface ___ <T> {
  [index: string]: T
}

After browsing through various stack overflow examples, I've come across names like StringIndexable, StringIndex, StrIndex, DictionaryIndex, Map, etc.

For my current project, I have chosen to name it ObjectMap. However, before implementing this in another project, I am curious if there is a recommended naming convention.

In ES6, there is the Map<K,V> class, but there are still scenarios where an indexed object is preferable even in new code.

Why do you think there isn't a standardized name for this type? The TypeScript handbook mentions that 'string index signatures are a powerful way to describe the “dictionary” pattern', but doesn't suggest using a generic return type.

Additionally, TypeScript offers the Record<Keys, Type> utility type which can be utilized as Record<string, T>. The handbook recommends using a union of strings for Keys without mentioning the option of using a catch-all string. While it technically works, it may contradict the intended use of the type. This brings us back to the question of what to name a type like

type ___<T> = Record<string, T>
. Perhaps spelling out Record<string, Foo> could be the solution.

So, is it common practice to fully specify the index type for each individual use case?

type Foo = any;
interface FooCollection {
    [index: string]: Foo;
}
function updateFooCollection(foos: FooCollection){}
// vs
function updateFooCollection(foos: ObjectMap<Foo>){}

Answer №1

A special type in TypeScript known as Record handles this functionality nicely. Your collection of Foo objects can be represented as Record<string, Foo>. Similarly, a generic collection with type T can be defined as Record<string, T>.

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

Ways to ensure that when changes occur in one component, another component is also updated

How can I update the cart badge value in the navbar component every time a user clicks the "Add to Cart" button in the product-list component? The navbar component contains a cart button with a badge displaying the number of products added to the cart. n ...

Integrating modules in Angular 2

Exploring the functionalities of Angularjs 2.0, I encountered an issue when attempting to inject a service into a class. Below is the code snippet that's causing trouble: import {Component, View, bootstrap, NgFor, HttpService, Promise} from 'ang ...

Using Typescript and React together does not permit the use of if statements with union types

I'm currently working on some code that looks like this // sample package export interface TCustomer { name: string; } import { TCustomer } from "some-package" interface BCustomer extends TCustomer { options: string; } type Props = { ...

Creating an HTTP method handler function in Next.js API routes with an unspecified number of generic parameters

Looking to create a wrapper function in NextJS for API routes that can handle multiple HTTP methods with different handlers. For example, check out the TS playground interface GetResponse { hello: string, } // empty object type PostResponse = Record&l ...

Encountering issues with updating subdocuments using mongoose

When attempting to update data from a subdocument using mongoose, I am encountering some issues Below is the data model: { status: 'regular', devices: [ { ip: 'deviceIp', active: true, _id: 5f4c05cb4708cf0e37a68ac0, ...

Encountering difficulties in creating a custom Response type in Express.js with TypeScript

I have encountered a TypeScript error while trying to create my own custom Response interface by extending some methods instead of using the default Response type of Express.js: The last overload resulted in the following error: Argument of type '(r ...

Is it possible to overlook specific attributes when constructing an object using TypeScript interfaces?

I have defined an interface with various properties. I am looking to instantiate an object based on this interface, but I only want to partially initialize some of the properties. Is there a way to accomplish this? Thank you. export interface Campaign { ...

How can you convert all nodes of a nested JSON tree into class instances in Angular 2 using Typescript?

I have a Leaf class that I want to use to convert all nodes in a JSON response into instances of Leaf. The structure of the JSON response is as follows: JSON Response { "name":"animal", "state":false, "children":[ { "name" ...

Utilize array mapping to alter the complete object

In my project using TypeScript (Angular 2), I am working on creating a "reset" method for an object array: cars [ { id: 1, color: white, brand: Ford, model: Mustang, ... }, ... ] Users have the ability to modify these objects, ...

Dealing with Nested Body Payload in PATCH Requests with Constructor in DTOs in NestJS

Within my NestJS environment, I have constructed a DTO object as follows: export class Protocol { public enabled?: boolean; public allowed?: boolean; constructor(enabled: boolean, allowed: boolean) { // With a necessary constructor this.enabled = ...

Is it possible to transform a tuple type into a union?

Is it possible to map a tuple's generic type to a union type? type TupleToUnion<T> = T[keyof T]; // This will include all values in the tuple const value: TupleToUnion<[7, "string"]> = 2; // This assignment should not be permitted since ...

Utilizing ES6 Promises in Mongoose with Typescript to Create a Seamless Chain

When attempting to chain ES6 promises with Mongoose 4.5.4, I encountered an error in Typescript. public static signup(req: express.Request, res: express.Response) { UserModel.findOne({ email: req.body.email }).exec() .then(existingUser => { ...

Enter a single unidentified character

As someone new to TypeScript, I have a question regarding my code. I am converting TypeScript into JavaScript to run in an environment where the window object has additional functions that I have declared on the TypeScript side like this: interface Window ...

Is there a glitch in the angular binding mechanism?

I am working with a component that includes a select option and a text input field. The purpose of the "select" is to choose a description of an object, while the input field is used to specify the quantity assigned to the selected object. In my form, I ne ...

Navigating through pop-ups in Chrome: A guide to using Protractor

Currently, I am utilizing Protractor and am faced with the challenge of handling a pop-up from Chrome. My goal is to successfully click on the button labeled "Open magnet URI". For a visual representation of the issue, refer to the following image: picture ...

Using ngModel to retrieve and display only the month, year, and date

Currently, I am working with an interface named Person which includes fields such as name, last name, birthday, and others. However, I am facing a confusion when it comes to the person's birthday format, as it contains some additional letters at the e ...

Unable to utilize checkboxes for filtering in Angular 2 and beyond

I am working on a project that involves showcasing a list of participants. My goal is to set up a feature that allows filtering these participants based on different providers using checkboxes in real-time. Below is a sample of the participants: [ { ...

Adjusting the selection in the Dropdown Box

I've been attempting to assign a value to the select box as shown below: <dx-select-box [items]="reportingProject" id="ReportingProj" [text]="reportingProject" [readOnly]="true" > ...

I encountered a TS error warning about a possible null value, despite already confirming that the value

In line 5 of the script, TypeScript raises an issue regarding the possibility of gameInstanceContext.gameInstance being null. Interestingly, this concern is not present in line 3. Given that I have verified its existence on line 1, it is perplexing as to w ...

Leveraging es6-promise in conjunction with TypeScript 2.1 and ES5 Webpack for streamlined async/await functionality

Utilizing es6-promise with TypeScript version 2.1.1 that targets ES5 and webpack in my project has presented some challenges. app.ts import "es6-promise/auto"; export class Foo { bar() : Promise<string>{ return Promise.resolve("baz"); ...