After encountering the same issue multiple times, I've decided it's time to address it:
How can functions that accept two different object types be defined in Typescript?
I've referred to https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html, and am aware that the standard union operator |
isn't ideal for objects as it only includes common elements.
An Example to Illustrate
type Person = {
name: string;
age: number;
};
type Pet = {
owner: string;
};
/*
* This function should accept two distinct object types as arguments
*/
const randomFunction = (myObject: Person | Pet) => {
// ISSUE:
// Property 'age' does not exist on type 'Person | Pet'.
if (typeof myObject.age !== 'undefined') console.log(myObject.age);
};
Issue: Property 'age' does not exist on type 'Person | Pet'.
How can this be resolved? I want to pass in different object types for a straightforward function.
Is what I'm attempting not in line with TypeScript conventions or is it discouraged?
To eliminate the TypeScript errors, it appears necessary to separate them into distinct functions.
Thank you!