Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!