Así que me he encontrado con este problema tantas veces que creo que es hora de preguntar:
¿Cómo se definen las funciones que toman dos tipos de objetos en Typescript?
También leí https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html y entiendo que el sindicato existente |
realmente no funciona bien para los objetos, ya que solo contendrá elementos que ambos objetos tienen.
Un ejemplo artificial
type Person = { name: string; age: number; }; type Pet = { owner: string; }; /* * We'd like this function to be able to take two different objects as args */ const randomFunction = (myObject: Person | Pet) => { // PROBLEM: // Property 'age' does not exist on type 'Person | Pet'. if (typeof myObject.age !== 'undefined') console.log(myObject.age); };
Problema: la propiedad 'edad' no existe en el tipo 'Persona | Mascota'.
Entonces, ¿cómo lidias con esto? Me gustaría poder pasar dos tipos de objetos diferentes para una función simple.
¿Lo que estoy tratando de hacer no es "TypeScripty" o no es recomendable?
Para deshacerme de los garabatos de TypeScript, parece que tendría que dividirlo en una función diferente.
¡Gracias!
Entonces, la solución es usar un TypeGuard según @Idruskis.
La solución está escrita en gran medida aquí: https://medium.com/ovrsea/checking-the-type-of-an-object-in-typescript-the-type-guards-24d98d9119b0
type Person = { name: string; age: number; }; type Pet = { owner: string; }; // Typeguard function isPerson( data: Pet | Person, ): data is Person { if ((data as Person).age) { return true; } return false; } const randomFunction = (myObject: Person | Pet) => { if (!isPerson(myObject)) return; // No error! if (typeof myObject.age !== 'undefined') console.log(myObject.age); };