Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

224
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda