Standardized identification code

My request response needs to be defined, but the key name may vary. It will always be a string, but the specific key depends on the request.

These are the possible responses:

{ someRequest: { message: 'success', status: 200 } }
{ someOtherRequest: { message: 'unauthorized', status: 401 } }

Considering that the someRequest key may change while the other remains constant, I attempted this:

export interface Response<T extends string> {
  [key: T]: { message: string; status: number; }
}

However, it resulted in an error - "An index signature parameter type must be either 'string' or 'number'". How can I define a generic key string?

Answer №1

To achieve the desired outcome, it is recommended to utilize [key in T] rather than [key: T]. However, interfaces do not support this operation, so consider switching to a type alias instead:

export type Response<T extends string> = {
    [key in T]: { message: string; status: number; };
};

Another option is to make use of the predefined Record type:

export type Response<T extends string> = Record<T, { message: string; status: number; };

Answer №2

You have the option of implementing a type utilizing the Record:

type Key = 'someRequest' | 'someOtherRequest';
type Response<T extends Key> = Record<T, { message: string; status: number; }>;

const foo: Response<'someRequest'> = {someRequest: {status: 200, message: 'success'}};
const bar: Response<'someOtherRequest'> = {someOtherRequest: {status: 401, message: 'unauthorized'}};

Alternatively, you can use

type Response<T extends string> = ...
which eliminates the necessity for Key. Another approach is to employ
type Key = 'someRequest' | 'someOtherRequest' | string;
in order to expand the keys.

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

I'm curious if anyone has experimented with implementing TypeScript enums within AngularJS HTML pages

During my Typescript project, I defined an enum like this: enum Action { None = 0, Registering = 1, Authenticating = 2 }; In the controller, I declared a property named action as follows: class AuthService implements IAuthService { action: number; ...

What is the best way to position Scroll near a mat row in Angular?

With over 20 records loaded into an Angular Material table, I am experiencing an issue where clicking on the last row causes the scroll position to jump to the top of the page. I would like the scroll position to be set near the clicked row instead. Is th ...

Struggling with the transformation: Failed to find import "child_process" in TypeScript

I encountered an issue when trying to run my simple TypeScript project. I am receiving the following error: 'Error while transforming Could not resolve import "child_process".' You can see the error in this screenshot. This error occurs in my tsc ...

How can I target and focus on a dynamically generated form in Angular 4/Ionic3?

One of the challenges I'm facing is dealing with dynamically created forms on a page. Each row consists of inputs and a button. Is there a way to select/focus on the input by clicking on the entire row (button)? It should be noted that the number of r ...

Utilize rest parameters for destructuring操作

I am attempting to destructure a React context using rest parameters within a custom hook. Let's say I have an array of enums and I only want to return the ones passed into the hook. Here is my interface for the context type enum ConfigItem { Some ...

What is the best way to securely store a sensitive Stripe key variable in an Angular application?

When implementing Stripe payment system in my Angular App, I often wonder about the security of storing the key directly in the code as shown below. Is this method secure enough or should I consider a more robust approach? var handler = (<any>windo ...

Ensuring accurate date formatting of API responses in TypeScript

My REST API returns data in the format shown below:- {"id": 1, "name": "New event", "date": "2020-11-14T18:02:00"} In my React frontend app, I have an interface like this:- export interface MyEvent { id ...

The imported path is not found in Tsconfig

Hey there! I've been working on getting my project's imports to play nice with typescript import paths. Every time I encounter this error : Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'app' imported from dist/index.js It seems l ...

Checking for undefined based on certain conditions

When looking at the following code snippet type stringUndefined = "string" | undefined; type What<T> = T extends undefined ? "true" : "false"; const no : What<stringUndefined> = ""; The value of ' ...

"Implemented a fresh pathway within the app-routing.module.ts file, but unfortunately, ngxAdmin is experiencing functionality issues

While customizing the ngx-admin template, I attempted to incorporate a new module into the app module and added its route in app-routing.module.ts. However, upon trying to open it, the module seems to be stuck at loading without any errors appearing in the ...

Creating a custom data type for the Tanstack table filtering function

I developed a unique filter function specifically for enhancing the functionality of Tanstack Table by utilizing fuse.js. Despite my efforts, TypeScript consistently raises concerns when I try to define the type for my custom function. My goal is to alig ...

The minimum and maximum validation functions are triggered when I am not utilizing array controls, but they do not seem to work when I use array controls

Take a look at the stack blitz example where min and max validation is triggered: https://stackblitz.com/edit/angular-mat-form-field-icrmfw However, in the following stack blitz with an array of the same controls, the validation does not seem to be worki ...

The mat-table's data source is failing to refresh and display the latest

When I click on a column header to sort the table, a function should trigger and update the data. However, the data is not updating as expected. Below is the code for the function and the table: <table mat-table #table [dataSource]="dataSourceMD&qu ...

Using LINQ with ngFor in Angular 6

Within the component.ts, I extract 15 different lookup list values and assign each one to a list, which is then bound to the corresponding <select> element in the HTML. This process functions correctly. Is there a method to streamline this code for ...

Pulling the month name based on a specific year and week using Javascript

In my HTML form, there are two fields called Year and Week. When the user chooses a Year and Week from the dropdowns, I would like to show the corresponding Month Name for that specific year and week. Is there anyone who can assist me in retrieving the m ...

Experiencing an error message stating 'The token ${Token[TOKEN.72]} is invalid' while using cdk synth, specifically when trying to assign the value of ec2.Vpc.cidr from cfnParameter.value

Attempting to utilize the AWS CDK CfnParameter to parameterize the CIDR value of ec2.Vpc. The aim is to make the stack reusable for VPC creation with the CIDR as a customizable value. An error stating "${Token[TOKEN.72]} is not valid" occurs during synthe ...

In TypeScript, the choice between using `private readonly` within a class and

I have been contemplating the best method and potential impacts of referencing constants from outside a class within the same file. The issue arose when I was creating a basic class that would throw an error if an invalid parameter was passed: export cla ...

Angular validation for password and confirmation password fields

I have been working on implementing password and confirm password validation within an angular project. I recently came across a helpful answer on this thread Confirm password validation in Angular 6 that I tried to follow. Unfortunately, I am encountering ...

Executing a Prisma query with a selection

My Prisma models involve User, Car, and Reservation entities: model User { id String @id @default(auto()) @map("_id") @db.ObjectId name String? email String? @unique emailVerified DateTime? image ...

Creating a function that operates according to the input parameter

Imagine a scenario where I am working with the following JS function: function fetchValue(keyName) { return x => x[keyName]; } Is it possible to define fetchValue in such a way that Typescript's type inference automatically determines the outp ...