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

131
Views
Atributo de interfaz de sobrecarga de mecanografiado

Imagina que tengo un montón de opciones de carga útil como:

 interface IOne { type: 'One', payload: { name: string, age: number } } interface ITwo { type: 'Two', payload: string } declare type TBoth = IOne | ITwo;

Entonces puedo recibir uno de los dos anteriores como parámetro. Quiero que el mecanografiado pueda reconocer los parámetros de cada tipo al usar un switch , por ejemplo.

El problema que tengo es cuando intento crear el objeto.

 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. }

Yo obtengo:

Los tipos de propiedad 'tipo' son incompatibles. Escriba '"Uno" | "Dos"' no se puede asignar al tipo '"Dos"'.

¿Es posible?

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

0

Puede reducir los tipos de uniones discriminadas de esta manera:

 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) } }

Ver un ejemplo en vivo

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!