I would like to define a response for my request however one thing might change and that's the key name. It's always going to be a string but it will be different depending on the request.
These are the possible responses
{ someRequest: { message: 'success', status: 200 } }
{ someOtherRequest: { message: 'unauthorized', status: 401 } }
Knowing the someRequest
might change but the other will not I have created this
export interface Response<T extends string> {
[key: T]: { message: string; status: number; }
}
but it does not work. I get the
An index signature parameter type must be either 'string' or 'number'
How do I define a generic key string?
CodePudding user response:
You have to use [key in T]
instead of [key: T]
. However, interfaces don't allow this operation, so switch to a type alias instead:
export type Response<T extends string> = {
[key in T]: { message: string; status: number; };
};
Alternatively, use the built-in Record
type:
export type Response<T extends string> = Record<T, { message: string; status: number; };
CodePudding user response:
You could use a type
using 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'}};
Though, type Response<T extends string> = ...
does also work, without the need of Key
. Or use type Key = 'someRequest' | 'someOtherRequest' | string;
to be able to extend the keys.