Home > Mobile >  Map set different types of value depending on key type in Typescript
Map set different types of value depending on key type in Typescript

Time:06-16

I want to use Map to implement a Trie, so I created a TrieNodeMap type. The TrieNodeMap has two types of keys: a single letter OR a '$' which means the end of a word. Key with a letter maps inner TrieNodeMap and '$' maps word's info object.

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'."

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?

CodePudding user response:

In order to do that, you need to overload your Map. In other words, you need to use intersection & instead of 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

  • Related