打字稿:如何根据联合类型在ES6地图中进行输入 [英] Typescript: How can I make entries in an ES6 Map based on a union type

查看:116
本文介绍了打字稿:如何根据联合类型在ES6地图中进行输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to use Map instead of object map to declare some keys and values. But Typescript doesn't seem to support index types for ES6 Map, is that correct and are there any workarounds?

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

Additionally, I would like to make the values type-safe as well so that each entry in the map has the correct type for the value corresponding to the key.

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

Here is some pseudo-code that describes what I am trying to achieve:

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],
]);

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

more code that partially describes my use case

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]
]);

推荐答案

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

Here's the closest I can imagine getting, although I still don't understand why we don't just use plain objects to begin with:

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).

The idea is to make a new interface, ObjectMap, which is specifically dependent on an object type O to determine its key/value relationship. And then you can say that the Map constructor can act as an ObjectMap constructor. I also removed any methods that can change which keys are actually present (and the has() method is redundantly true also).

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

I can go through the trouble of explaining each method and property definition, but it's a lot of type-juggling. In short you want to use K extends keyof O and O[K] to represent the types normally represented by K and V in Map<K, V>.

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

The constructor is a bit more annoying in that type inference doesn't work the way you'd like, so guaranteeing type safety comes in two steps:

// 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会给您错误.

If your myMapInferredType doesn't match ObjectMap<Values> (e.g., you are missing keys or have the wrong value types) then myMap will give you errors.

现在,您可以将myMap用作ObjectMap<Values>,类似于将Map实例与get()set()一起使用的方式,并且它应该是安全的.

Now you can use myMap as an ObjectMap<Values>, similarly to how you'd use a Map instance, with get() and set(), and it should be type safe.

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

Please note again... this seems like a lot of work for a more complex object with trickier typings and no more functionality than a plain object. I would seriously warn anyone using a Map whose keys are subtypes of keyof any (that is, string | number | symbol) to strongly consider using a plain object instead, and be sure that your use case really necessitates a Map.

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

Okay, hope that helps you. Good luck!

这篇关于打字稿:如何根据联合类型在ES6地图中进行输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆