是否可以在TypeScript中创建通用的映射对象类型?

时间:2020-03-29 11:55:56

标签: typescript typescript-generics

我有两组相似的打字稿定义:

enum Operation1 {
  eof = 'eof',
  bof = 'bof'
}
type OperationConfig1 = { [key in Operation1]: TestBedConfig };

enum Operation2 {
  append = 'append',
  prepend = 'prepend'
}
type OperationConfig2 = { [key in Operation2]: TestBedConfig };

我可以按以下方式使用它们:

const config1: OperationConfig1 = {
  [Operation1.eof]: { ... },
  [Operation1.bof]: { ... }
};

const config2: OperationConfig2 = {
  [Operation2.append]: { ... },
  [Operation2.prepend]: { ... }
};

我想用一种通用类型OperationConfig1替换OperationConfig2OperationConfig,并以某种形式接受Operation作为参数

type OperationConfigGeneric<T> = { [key in T]: TestBedConfig };

const config1: OperationConfigGeneric<Operation1> = { ... };
const config2: OperationConfigGeneric<Operation2> = { ... };

以上代码无效,并引发以下异常:

TS2322:类型“ T”不可分配给类型“字符串|编号|
符号'。不能将类型“ T”分配给类型“符号”。

问题。如何参数化映射的对象类型(OperationConfigGeneric)?还是有其他方便的选择?

1 个答案:

答案 0 :(得分:1)

您可以执行此操作,但是仅当类型参数T是可以作为属性键的值时才有可能。因此,如果您以PropertyKey为上限声明T,它将起作用。

type OperationConfigGeneric<T extends PropertyKey> = {
    [key in T]: TestBedConfig
};

const config1: OperationConfigGeneric<Operation1> = { ... };