自定义记录键的打字稿类型

问题描述 投票:0回答:0

我正在尝试编写一个小型库,我想在其中为以下对象添加类型安全:

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

现在我想做的是获取对象键的类型安全列表

ErrorCodeMap
.

如果我执行以下操作

export type ErrorCode = keyof typeof ErrorCodeMap;

ErrorCode
的类型等于
string
。我希望它等于
'NOT_FOUND' | 'ALREADY_EXISTS'
.

我尝试使用

as const
synthax,但我觉得我在这里有点偏离。

有没有办法在不删除

Record<string, [string, number]>
定义的情况下解决这个问题,从而在对象定义上保留类型安全?

typescript type-conversion record
© www.soinside.com 2019 - 2024. All rights reserved.