我想创建一个错误代码计数器,但是使用枚举和泛型在打字稿方面遇到问题。
这是有效版本(没有通用名称)
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
我们如何制作通用的 Counter 界面,用作:
const counter = <Counter<ErrorCode>>{}
counter[ErrorCode.MX1] = 3
想到的一种方法是
type Counter<T> = {
[code in keyof T] : number
}
但这不起作用。 有什么想法可以制作通用版本吗?
注意,可以用接口替换枚举,但是我更喜欢枚举而不是接口
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.
答案 0 :(得分:1)
您不需要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