How to make a lists of multiple data types with overlapping IDs

I have types Foo and Bar and I want to show a list containing elements of both. The problem is that both Foo and Bar begin incrementing IDs from 0, so I can't set key={foobar.id} . I would like each key to be foo-${foobar.id} if the object is of type Foo OR bar-${foobar.id} if the object is of type Bar. I tried Googling this and I tried instanceof and is in a ternary, but I still couldn't get it to work.
2 Replies
Neto
Neto17mo ago
type Foo = {
id: number;
prop1: string;
};

type Bar = {
id: number;
prop2: string;
};

const getKey = (data: Foo | Bar): string => {
if ("prop1" in data) {
return `foo-${data.id}`;
}

return `bar-${data.id}`;
};
type Foo = {
id: number;
prop1: string;
};

type Bar = {
id: number;
prop2: string;
};

const getKey = (data: Foo | Bar): string => {
if ("prop1" in data) {
return `foo-${data.id}`;
}

return `bar-${data.id}`;
};
Neto
Neto17mo ago
No description
Want results from more Discord servers?
Add your server