Take a look at the code snippet below. The function getStatusDescription
is designed to return a description for a given HTTP status code if it exists in the predefined list, otherwise it returns the status code itself.
const StatusDescription = {
200: 'ok',
400: 'bad request',
500: 'internal server error',
}
const getStatusDescription(status: string) = {
return StatusDescription[status] || status
}
An error occurs at the return statement:
Element implicitly has an 'any' type because expression of type 'string' cannot be used to index type '{ 200: string; 400: string; 500: string; }'.
No index signature with a parameter of type 'string' was found on type '{ 200: string; 400: string; 500: string; }'. (7053)
A suggested fix involves setting
StatusDescription: Record<string, string> = …
, but this would extend the key type of the object to include all possible strings, which is not desirable.
Attempting to use
return status in StatusDescription ? StatusDescription[status] : status
results in the same TypeScript error. Therefore, manual type conversion is necessary:
return (
status in StatusDescription
? StatusDescription[status as unknown as keyof typeof StatusDescription]
: status
)
This solution is quite verbose. A shorter and potentially incorrect alternative approach is:
return (
StatusDescription[status as unknown as keyof typeof StatusDescription]
|| status
)
Although this does not generate any errors, it raises concerns about whether status
truly corresponds to a keyof StatusDescription
during the type conversion process.
Is there a more concise solution available (similar to obj[key] || key
) that still provides type safety?