TypeScript: ¿Cómo crear un tipo condicional que devuelva un arreglo según la condición?
Estoy tratando de escribir una función que debería devolver un tipo de arreglo, si el parámetro de entrada es de tipo arreglo, y un parámetro normal de lo contrario. Aquí está mi intento:
function test<T extends number|number[]>(a: T):T extends number[] ? string[] : string {
if (Array.isArray(a)) {
return ['123', '45']
}
return '123'
}
Obtengo un error en las instrucciones return: Type 'string' is not assignable to type 'T extends number[] ? string[] : string'.
Lo que estoy buscando es lo siguiente:
const a = test(3) // "a" is string type
const b = test([1,2,3]) // "b" is string[] type
Respuesta #1
Simplemente sobrecarga tu función:
function test(a: number): '123'
function test(a: number[]): string[]
function test<T extends number | number[]>(a: T) {
if (Array.isArray(a)) {
return ['123', '45']
}
return '123'
}
test(2) // '123'
test([23]) // string[]
No hay necesidad en tipos condicionales.
Parque infantil
Respuesta #2
Basado en esto, Typescript no inferirá diferentes tipos de retorno basados en guardias de tipo en la función. Pero puedes definir múltiples firmas de función así:
function test(a: number): string;
function test(a: number[]): string[];
function test<T extends number|number[]>(a: T): string | string[]{
if (Array.isArray(a)) {
return ['123', '45']
}
let str = '123'
return str;
}
const a = test(3) //string
const b = test([1,2,3]) //string[]
PlaygroundLink
También vea este problema: https://github.com/microsoft/TypeScript/issues/24929
