打字稿:如何根据联合类型在ES6地图中进行输入

时间:2019-02-27 13:51:44

标签: typescript ecmascript-6 typescript-generics union-types es6-map

我想使用Map而不是对象map来声明一些键和值。但是Typescript似乎不支持ES6 Map的索引类型,这是正确的,并且有任何解决方法吗?

此外,我还要使值的类型安全,以便映射中的每个条目都具有与键对应的值的正确类型。

以下是一些伪代码,描述了我要实现的目标:

type Keys = 'key1' | 'key2';

type  Values = {
  'key1': string;
  'key2': number;
}

/** Should display missing entry error */
const myMap = new Map<K in Keys, Values[K]>([
  ['key1', 'error missing key'],
]);

/** Should display wrong value type error for 'key2' */
const myMap = new Map<K in Keys, Values[K]>([
  ['key1', 'okay'],
  ['key2', 'error: this value should be number'],
]);

/** Should pass */
const myMap = new Map<K in Keys, Values[K]>([
  ['key1', 'all good'],
  ['key2', 42],
]);

编辑:更多代码可以部分描述我的用例

enum Types = {
  ADD = 'ADD',
  REMOVE = 'REMOVE',
};

/** I would like type-safety and autocompletion for the payload parameter */
const handleAdd = (state, payload) => ({...state, payload});

/** I would like to ensure that all types declared in Types are implemented */
export const reducers = new Map([
  [Types.ADD, handleAdd],
  [Types.REMOVE, handleRemove]
]);

1 个答案:

答案 0 :(得分:2)

这是我能想象得到的最接近的东西,尽管我仍然不明白为什么我们不只是以普通对象开头:

type ObjectToEntries<O extends object> = { [K in keyof O]: [K, O[K]] }[keyof O]

interface ObjectMap<O extends object> {
  forEach(callbackfn: <K extends keyof O>(
    value: O[K], key: K, map: ObjectMap<O>
  ) => void, thisArg?: any): void;
  get<K extends keyof O>(key: K): O[K];
  set<K extends keyof O>(key: K, value: O[K]): this;
  readonly size: number;
  [Symbol.iterator](): IterableIterator<ObjectToEntries<O>>;
  entries(): IterableIterator<ObjectToEntries<O>>;
  keys(): IterableIterator<keyof O>;
  values(): IterableIterator<O[keyof O]>;
  readonly [Symbol.toStringTag]: string;
}

interface ObjectMapConstructor {
  new <E extends Array<[K, any]>, K extends keyof any>(
    entries: E
  ): ObjectMap<{ [P in E[0][0]]: Extract<E[number], [P, any]>[1] }>;
  readonly prototype: ObjectMap<any>;
}

const ObjectMap = Map as ObjectMapConstructor;

此想法是创建一个新接口ObjectMap,该接口具体取决于对象类型O,以确定其键/值关系。然后您可以说Map构造函数可以充当ObjectMap构造函数。我还删除了任何可以更改实际存在的键的方法(并且has()方法也是多余的true)。

我可以解释每个方法和属性定义的麻烦,但这要花很多时间。简而言之,您想使用K extends keyof OO[K]来表示通常由K中的VMap<K, V>表示的类型。

构造函数有点烦人,因为类型推断无法按您希望的方式工作,因此保证类型安全性分两个步骤:

// let the compiler infer the type returned by the constructor
const myMapInferredType = new ObjectMap([
  ['key1', 'v'], 
  ['key2', 1],  
]);

// make sure it's assignable to `ObjectMap<Values>`: 
const myMap: ObjectMap<Values> = myMapInferredType;

如果您的myMapInferredTypeObjectMap<Values>不匹配(例如,您缺少键或值类型错误),那么myMap会给您带来错误。

现在,您可以将myMap用作ObjectMap<Values>,类似于使用Mapget()的{​​{1}}实例,并且应该输入安全类型。

请再次注意...对于一个复杂的对象,键入起来比较棘手,并且没有比普通对象更多的功能,这似乎需要做很多工作。我会严重警告使用set()的键是Map(即keyof any的子类型)的任何人,强烈建议改为consider using a plain object,并确保您的用例确实有必要string | number | symbol

好的,希望对您有所帮助。祝你好运!