简体   繁体   English

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

[英]Is it possible to make generic mapped object type in TypeScript?

I have two similar groups of typescript definitions:我有两组相似的打字稿定义:

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

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

I can use them as following:我可以使用它们如下:

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

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

I want to replace OperationConfig1 and OperationConfig2 with one generic type OperationConfig accepting Operation as a parameter in some form like我想用一种通用类型OperationConfig替换OperationConfig1OperationConfig2 ,它接受Operation作为某种形式的参数,例如

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

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

The above code is invalid and throws following exception:上面的代码无效并抛出以下异常:

TS2322: Type 'T' is not assignable to type 'string | TS2322:类型 'T' 不能分配给类型 'string | number |数量 |
symbol'.象征'。 Type 'T' is not assignable to type 'symbol'.类型“T”不可分配给类型“符号”。

The question.问题。 How can I parametrize mapped object type (OperationConfigGeneric)?如何参数化映射对象类型 (OperationConfigGeneric)? Or is there any convenient alternative?或者有什么方便的替代方法?

You can do this, but it is only possible when the type parameter T is something that can be a property key.你可以这样做,但只有当类型参数 T 是可以作为属性键的东西时才有可能。 So, if you declare T with PropertyKey as an upper bound, it works.所以,如果你用 PropertyKey 作为上限声明 T,它就可以工作。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM