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

156
Visualizações
How to enforce generic types typescript function

I have the following function signature:

const renderMessage = <T extends A | B > 
(
  a: T,
  b: Map<T, Array<string>>, 
  c: T,
) => {

My problem is that I can call this function as follows:

type A = "A" | "B"
type B = "Z" | "Y"
let myA: A = "A"
let myB: B = "Z"
let myAMap: Map<A,Array<string>> = new Map(...)
let myBMap: Map<B,Array<string>> = new Map(...)
renderMessage(myA, myBMap, myA) // I want error here
renderMessage(myB, myAMap, my B) // I want error here

The reason for being able to do this is explained here. If I understood correctly, the structure of my Map object does not change based on T being A or B, so typescript won't complain. However, I am struggling to figure out how to enforce this.

EDIT

They are types and not classes. See Playground Link

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The T type is too ambiguous for the TypeScript inference. It resolves to the most narrow type that satisfies the whole signature: A | B.

I guess you just have to provide it yourself between angle brackets:

TypeScript playground

about 4 years ago · Juan Pablo Isaza Relatório

0

The reason to have different classes - A and B - should be if one type of instance should hold differently structured data from the other, or if one type of instance should have different methods. If the data is structured the same way, and the methods are all the same as well, then there shouldn't be separate classes.

If you distinguish A and B in any way, the error will arise as desired:

class A{
  x = 'x'
}
class B{
  y = 'g'
}
const renderMessage = <T extends A | B > 
(
  a: T,
  b: Map<T, Array<string>>, 
  c: T,
) => {
}

let myA: A = new A()
let myB: B = new B()
let myAMap: Map<A,Array<string>> = new Map(...)
let myBMap: Map<B,Array<string>> = new Map(...)
renderMessage(myA, myBMap, myA) // I want error here
renderMessage(myB, myAMap, myB) // I want error here
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