I am facing a challenge with a simple use case and have been unable to find an example that covers it adequately.
The situation is this: I have a function that should accept two different objects that are very similar. Therefore, I want to use a generic type. Here is how the function looks:
const myFunction = <MyGenericType>(arrayOfObjects: MyGenericType[]) => {
return arrayOfObjects.map((obj: MyGenericType) => ({
id: obj.id,
name: obj.name,
someProperty: obj.someProperty || obj.someOtherProperty,
}))
}
These are the two types that I could pass as parameters for this function:
type PotentialType1 = {
id: string
name: string
someProperty: string
}
type PotentialType2 = {
id: string
name: string
someOtherProperty: string
}
The issue arises when trying to access properties in myFunction
, resulting in an error:
Property X does not exist on type 'MyGenericType'.
This occurs for id, name, and someProperty. While it works fine with primitive types like string or number, complex types pose a challenge.
Any assistance would be greatly appreciated!