Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

129
Vistas
Typescript overload interface attribute

Imagine I have a bunch of payload options like:

interface IOne {
  type: 'One',
  payload: {
    name: string,
    age: number
  }
}

interface ITwo {
  type: 'Two',
  payload: string
}

declare type TBoth = IOne | ITwo;

So I can receive one of the two above as parameter. I want the typescript to be able to recognize the parameters of each type when using a switch for example.

The problem I'm having is when I'm trying to Create the object.

const value = req.body?.message; // just an example
const test: TBoth = {
  type: value ? 'One' : 'Two,  // <--- Now it should autocomplete/suggest the rights parameters based on this attribute.
}

I get:

Types of property 'type' are incompatible. Type '"One" | "Two"' is not assignable to type '"Two"'.

Is it possible?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can narrow the types of discriminated unions like this:

const doSomething = (test: TBoth) => {
  if(test.type === `One`) {
    // hover the below `test` with VSCode you will see:
    //   (parameter) test: IOne
    handleIOne(test)
  } else {
    // hover the below `test` with VSCode you will see:
    //   (parameter) test: ITwo
    handleITwo(test)
  }
}

See a live example

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda