I need assistance in setting the key type of an object. Here is what I have tried:
type TypeSample = {
[key: string]: string
}
In addition, I want to specify that the keys should come from an enum like this:
enum EnumSample {
'ok' = '200',
}
type TypeSample = {
[key in EnumSample]: string
}
If I do not set the key type, I encounter the error
'Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'TypeSample'
when using my "getter" function.
My Inquiry: How can I adjust "TypeSample" so that TypeScript recognizes it will only contain string keys?
Please note: It is crucial for other parts of the code that "EnumSample" remains an ENUM and not a TYPE/INTERFACE.
Context:
Here is a simplified version of the code I am dealing with:
enum SupportedHttpStatuses {
'ok' = '200',
'badRequest' = '400',
'imATeapotSafe' = '418a',
'imATeapot' = '418b',
}
type StatusMapType = {
[key in SupportedHttpStatuses]: StatusType // My aim is to define the key type here
}
type StatusType = {
code: number, // status code to send to the browser
title: string, // error title
description: string // error description
}
class Test {
public static STATUS_MAP: StatusMapType = {
'200': {
code: 200,
title: 'OK',
description: 'This request has succeeded.',
},
'400': {
code: 400,
title: 'Bad Request',
description: 'This request is missing data or contains invalid information.',
},
'418a': {
code: 200,
title: 'I\'m A Teapot!',
description: 'This request was successful but it is april fools day.',
},
'418b': {
code: 418,
title: 'I\'m A Teapot!',
description: 'This request was successful but it is april fools day.',
},
}
public static async getStatusMap(statusId: string): Promise<StatusType> {
return this.STATUS_MAP[statusId] // Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'StatusMapType'
}
}