Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript type for custom Record keys

I am trying to write a small library where I want to add type safety to the following object:

export const ErrorCodeMap: Record<string, [string, number]> = {
  NOT_FOUND: ['1001', 222],
  ALREADY_EXISTS: ['1002', 111],
}

Now what I want to do is to get a type-safe list of the keys of the object ErrorCodeMap.

If I do the following

export type ErrorCode = keyof typeof ErrorCodeMap;

the type of ErrorCode is equal to string. I would like it to equal 'NOT_FOUND' | 'ALREADY_EXISTS'.

I tried to use the as const syntax but I think I am a bit off here.

Is there any way to solve this WITHOUT removing the Record<string, [string, number]> definition and thus retaining type safety on the object definition?

like image 402
Max101 Avatar asked Nov 01 '25 07:11

Max101


1 Answers

This approach gives you a suitable type...

export const ERROR_MAP = {
  NOT_FOUND: ['1001', 222],
  ALREADY_EXISTS: ['1002', 111],
} as const satisfies Record<string, readonly [string, number]>

// hover to reveal type ErrorCode = "NOT_FOUND" | "ALREADY_EXISTS"
type ErrorCode = keyof typeof ERROR_MAP;

Typescript Playground

like image 70
cefn Avatar answered Nov 03 '25 01:11

cefn