I am facing an issue with TypeScript:
type Foo = {
a: number
}
type Bar = {
b: number
}
type Props = {
object?: Foo | Bar | null;
keys?: (keyof Foo)[] | (keyof Bar)[];
}
function myFunction({ object, keys = ['a'] }: Props) {
const values = keys.map(key => object && object[key]);
// Element implicitly has an 'any' type because expression of type '"a" | "b"' can't be used to index type 'Foo | Bar'.
// Property 'b' does not exist on type 'Foo | Bar'.
}
What approach would you take to define types for a situation where the inputs can be either of type Foo or Bar?
I am working on creating an abstraction that can accept two objects and specific keys to extract from those objects. The input objects could be of type A or C. They may have varying keys, but the user is expected to provide the corresponding keys based on the object passed.