简体   繁体   English

Map 根据 Typescript 中的键类型设置不同类型的值

[英]Map set different types of value depending on key type in Typescript

I want to use Map to implement a Trie, so I created a TrieNodeMap type.我想用 Map 来实现一个 Trie,所以我创建了一个 TrieNodeMap 类型。 The TrieNodeMap has two types of keys: a single letter OR a '$' which means the end of a word. TrieNodeMap 有两种类型的键:单个字母或“$”,表示单词的结尾。 Key with a letter maps inner TrieNodeMap and '$' maps word's info object.带有字母的键映射内部 TrieNodeMap 和 '$' 映射单词的信息对象。

This is what I wrote:这是我写的:

type Char = 'a' | 'b' | 'c' | 'd' // just name a few chars;
type TrieNodeMap = Map<Char, TrieNodeMap> | Map<'$', object>;

However, when I try to use it, the editor shows an error around 'a' as Char : "TS2345: Argument of type 'string' is not assignable to parameter of type 'never'."但是,当我尝试使用它时,编辑器在'a' as Char :“TS2345:'string' 类型的参数不可分配给'never' 类型的参数。”

let node: TrieNodeMap = new Map();
node.set('a' as Char, new Map());

Have I done something wrong, why it seems that the key of TrieNodeMap is a never type?我是不是做错了什么,为什么 TrieNodeMap 的键似乎是 never 类型?

In order to do that, you need to overload your Map .为此,您需要重载Map In other words, you need to use intersection & instead of union |换句话说,你需要使用交集&而不是 union |

type Char = 'a' | 'b' | 'c' | 'd' // just name a few chars;
type TrieNodeMap = Map<Char, TrieNodeMap> & Map<'$', object>;

let node: TrieNodeMap = new Map();
node.set('a', new Map());

const trie = node.get('b') // TrieNodeMap | undefined
const obj = node.get('$') // object | undefined

Playground操场

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

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