¿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
¿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 2Sin 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 2Puede usar una función que simplemente extrae el primer tipo de elemento del resto de parámetros.
undefined porque el tipo del primer argumento es (implícitamente) undefinedT | undefined , así será el tipo de retornoT , también lo será el tipo de retorno 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