An ordinary array by itself does not possess attributes that distinguish its elements' types.
Nevertheless, you have the option to utilize a functional type guard for verifying at runtime whether the elements of the array adhere to the anticipated type. Subsequently, you can safely execute property access operations within the filter callback function:
TS Playground
function arrayItemsHaveProperty<P extends PropertyKey>(
array: object[],
prop: P,
): array is Record<P, unknown>[] {
return array.every((o) => prop in o);
}
interface TypeA {
attribute1: string;
attribute2: string;
}
interface TypeB {
attribute3: string;
attribute4: string;
}
function fitlerFunc(obj: TypeA[] | TypeB[]) {
if (arrayItemsHaveProperty(obj, "attribute1")) {
return obj.filter((item) => item.attribute1 === "test");
// ^? (parameter) obj: TypeA[]
}
return obj.filter((item) => item.attribute3 === "something");
// ^? (parameter) obj: TypeB[]
}
It should be noted that this method prioritizes simpler syntax over performance (resulting in two iterations of the array) — you can achieve it in a single iteration, but type assertions would be necessary. The decision depends on the specifics of your particular usage scenario.