Search code examples
typescripttype-conversionrecord

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?


Solution

  • 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