Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading