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

186
Views
Cómo hacer un tipo depende del argumento

¿Es posible hacer que el tipo de retorno de la función dependa del tipo de argumento?

 const exampleFunction<T> = (initial?: T, ...anotherArgs) => { ...Some logic }

En este ejemplo por defecto podemos usar T | indefinido, pero necesito que el tipo de función de retorno siempre sea T si los datos iniciales están definidos y (T | indefinido) si no está definido

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

0

¿Es posible hacer que el tipo de retorno de la función dependa del tipo de argumento?

Esta pregunta en un sentido general generalmente se responde con sobrecargas de funciones.

En este caso podrías hacer algo como:

 function exampleFunction<T>(initial: T): T // overload 1 function exampleFunction(initial?: undefined): undefined // overload 2 // Implementation function exampleFunction<T>(initial?: T): T | undefined { return initial } const a: { abc: number } = exampleFunction({ abc: 123 }) // use overload 1 const b: undefined = exampleFunction() // use overload 2 const c: undefined = exampleFunction(undefined) // use overload 2

Patio de juegos


Sin embargo, leyendo tu pregunta con más cuidado...

siempre sea T si los datos iniciales están definidos y (T | indefinido) si no está definido

Puede cambiar la segunda sobrecarga a:

 function exampleFunction<T>(initial?: undefined): T | undefined // overload 2

Pero eso requerirá un tipo manual para T ya que no se puede inferir ninguno.

 const b: { def: string } | undefined = exampleFunction<{ def: string }>() // use overload 2

Patio de juegos

about 4 years ago · Juan Pablo Isaza Report

0

Puede usar una función que simplemente extrae el primer tipo de elemento del resto de parámetros.

  • Si no se proporcionan argumentos, el tipo de retorno será undefined porque el tipo del primer argumento es (implícitamente) undefined
  • Si el primer argumento es T | undefined , así será el tipo de retorno
  • Si el primer tipo de argumento es T , también lo será el tipo de retorno

Parque infantil TS

 function typeOfFirstArgument <Args extends readonly any[]>(...args: Args): Args[0] { const [first] = args; // ... return first; } const result1 = typeOfFirstArgument(); // undefined const result2 = typeOfFirstArgument('ok', 'another'); // string const result3 = typeOfFirstArgument(...['ok', 'another'] as const); // "ok" const result4 = typeOfFirstArgument({ msg: 'hello world' }, ['foo', 'bar']); // { msg: string } let value: string | undefined; const result5 = typeOfFirstArgument(value); // string | undefined
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!