如何在 TypeScript 中创建一个 Record<>(或其他映射)键控到一个枚举作为联合

How to create a Record<> (or other mapping) in TypeScript keyed to an enum as a union

我需要创建键控到枚举的函数映射,但如果我使用 Record<> 实用程序类型,它似乎需要 all 枚举值存在于映射对象。我需要它们都是可选的。例如:

enum ContentType {
  Text,
  Image,
  Video,
}
type MapFn = (value: string) => string;

type ContentTypeMap = Record<ContentType, MapFn>;

const myMap = {
  [ContentType.Text] : (value:string) => (value.toUpperCase),
} as ContentTypeMap;

结果:

Conversion of type '{ 0: (value: string) => () => string; }' to type 'ContentTypeMap' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  Type '{ 0: (value: string) => () => string; }' is missing the following properties from type 'ContentTypeMap': 1, 2

我也简单试过:

type ContentMap = { [ContentType]: MapFn };

但是编译器抱怨使用 ContentType:

A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.

我认为枚举算作文字,但我想在这种情况下不是?

我可以使用什么来创建对象不需要实现所有枚举值的 (enum) => (function) 映射?

I also tried simply:

type ContentMap = { [ContentType]: MapFn };

你很接近,但它需要是这样的:

type ContentMap = { [key in ContentType]: MapFn };

然后将它们设为可选:

type ContentMap = { [key in ContentType]?: MapFn };

Playground link

如果您更喜欢使用 Record 表示法,则可以使用实用程序类型 Partial 使其所有属性都可选:

type ContentMap = Partial<Record<ContentType, MapFn>>;

Playground Link