javascript - Typescript : Es6 Map TS Type Relation
问题描述
Is it possible to create a sort of relation between the Key/Value types of Map ?
I mean, if I use an object, it's easy to create something like :
type TObject = { key: string; value: number } | { key: number; value: string }
const obj = { key: 1, value: 'Something' } // Perfect
const obj = { key: 'Something', value: 1 } // Perfect
const obj = { key: 1, value: 1 } // Error
However, I don't know how to implement this behavior for Maps
const map = new Map<string | number, number | string>();
map.set(1, 'a'); // Perfect
map.set('a', 1); // Perfect
map.set(1, 1); // I want to display an error, with the type above : this will works since <number, number> is a possible type
map.set('a', 'a'); // I want to display an error, currently this will works since <string, string> is a possible type
解决方案
Define a custom type that overrides Map
to direct the call signatures to what you want.
interface CustomMap<T, U> extends Map<T | U, T | U> {
get(key: T): U | undefined;
get(key: U): T | undefined;
set(key: T, value: U): this;
set(key: U, value: T): this;
}
const map: CustomMap<string, number> = new Map();
map.set(1, 'a'); // OK
map.set('a', 1); // OK
map.set(1, 1); // error as expected
map.set('a', 'a'); // error as expected
map.size; // OK, not overridden, still a number
map.delete(1); // OK
map.delete('a'); // OK
推荐阅读
- python - 储蓄情绪分析模型
- r - 与多变量条件 R 配对
- google-chrome-extension - 为什么我没有收到来自 Node.JS Native App 到我的 chrome 扩展的任何消息?
- forms - MS Access:显示存储在表格中的图片/徽标作为附件
- wordpress - Wordpress - 按分类挂钩预加载术语页面
- ruby-on-rails - 在 Raisl 6 中从 git 中删除 node_modules 后推送失败
- windows - 如何修复 CURL 错误“无法解析主机”?
- r - 如何在保持R格式的同时将表达式转换为字符
- c++ - 当 std::optional 和 boost::optional 的值是变体时的区别
- java - Cordova 应用程序在从另一个活动返回时使用回调时崩溃