genéricos - Inferir el tipo base para dos argumentos en Typescript
Mientras implementaba una función genérica sobre conjuntos en Typescript, noté que el compilador no puede inferir el tipo base de dos argumentos.
function union<T>(first: Set<T>, second: Set<T>): Set<T> {
const newSet = new Set<T>(first);
for (const element of second)
newSet.add(element);
return newSet;
}
class Animal { }
class Dog extends Animal {
bark() { console.info('Woof!'); }
}
class Cat extends Animal {
meow() { console.info('Meow!'); }
}
const a = new Set<Dog>();
const b = new Set<Cat>();
Luego, si llamo a union, Typescript no puede inferir que T debería ser Animal.
const c = union(a, b);
// This results in the error:
// Argument of type 'Set<Cat>' is not assignable to parameter of type 'Set<Dog>'.
// Property 'bark' is missing in type 'Cat' but required in type 'Dog'.ts(2345)
Pero si llamo explícitamente a union con T=Animal, funciona bien:
const d = union<Animal>(a, b);
¿Qué estoy haciendo mal?
Respuesta #1
Intenta usar la unión de tipos:
function union<T extends Animal, U extends Animal>(first: Set<T>, second: Set<U>) {
const newSet = new Set<T | U>(first);
for (const element of second)
newSet.add(element);
return newSet;
}
class Animal { }
class Dog extends Animal {
bark() { console.info('Woof!'); }
}
class Cat extends Animal {
meow() { console.info('Meow!'); }
}
const a = new Set<Dog>();
const b = new Set<Cat>();
const c = union(a, b);
Parque infantil
Agregar un argumento genérico adicional U ayuda a TS a inferir el tipo de ambos Set
