使用带有泛型的 keyof 枚举的打字稿

sbr*_*sbr 4 enums typescript typescript-generics typescript-typings

我想创建一个错误代码计数器,但使用枚举和泛型的打字稿有问题。

这是工作版本(没有泛型)

enum ErrorCode  {
    MX1 = 'MX1',
    MX2 = 'MX2'
}

type Codes = keyof typeof ErrorCode;
type ErrorCodeCounter = {
    [code in Codes]: number
}

const counter = <ErrorCodeCounter>{}
counter[ErrorCode.MX1] = 3
counter['randomCode'] = 3 // Valid TS error: 'randomCode' does not exist on type 'ErrorCodeCounter
Run Code Online (Sandbox Code Playgroud)

我们怎样才能制作一个通用的Counter接口,用作:

const counter = <Counter<ErrorCode>>{}
counter[ErrorCode.MX1] = 3
Run Code Online (Sandbox Code Playgroud)

我想到的一种方法是

type Counter<T> = {
    [code in keyof T] : number
}

Run Code Online (Sandbox Code Playgroud)

但这不起作用。有什么想法如何制作通用版本吗?

请注意,用接口替换枚举是可行的,但我更喜欢枚举而不是接口

interface ErrorCodeI {
    MS1: string;
    MS2: string;
}

type Counter<T> = {
    [code in keyof T] : number
}
const counter = <Counter<ErrorCodeI>>{}
counter['MS1'] = 3
counter['random'] = 3 // Valid TS error.
Run Code Online (Sandbox Code Playgroud)

Tit*_*mir 6

您不需要keyof,枚举类型本身已经是您想要映射的枚举元素的并集:

type Counter<T extends PropertyKey> = {
    [code in T] : number
}


enum ErrorCode  {
    MX1 = 'MX1',
    MX2 = 'MX2'
}

const counter = <Counter<ErrorCode>>{}
counter[ErrorCode.MX1] = 3
counter['randomCode'] = 3 //ERR
Run Code Online (Sandbox Code Playgroud)

游乐场链接

  • 这很棒。不知道 PropertyKey 并且无法在文档中找到它。如果您知道的话,请分享任何具有更多背景信息的资源。谢谢。 (2认同)